首页 > 其他 > 详细

LeetCode OJ:Best Time to Buy and Sell Stock(股票买卖的最佳时期)

时间:2015-10-14 23:33:11      阅读:298      评论:0      收藏:0      [点我收藏+]

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

简单的动态编程问题,可是一开始我没读懂题目的意思。这里的买入当然应该在卖出之前,所以说不是那种取一个max一个min相减就能解决的,代码如下:

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int sz = prices.size();
 5         if(sz == 0 || sz == 1) return 0;
 6         int min, maxGain;
 7         min = prices[0];//min的初值要注意
 8         maxGain = 0;
 9         for(int i = 0 ; i < sz; ++i){
10             if(min > prices[i])
11                 min = prices[i];
12             else if(maxGain < prices[i] - min)
13                 maxGain = prices[i] - min;
14         }
15         return maxGain;
16     }
17 };

 

LeetCode OJ:Best Time to Buy and Sell Stock(股票买卖的最佳时期)

原文:http://www.cnblogs.com/-wang-cheng/p/4878996.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!