您的位置:首页 > 编程语言 > C语言/C++

leetcode #121 in cpp

2016-06-19 06:57 357 查看
Solution:

We should look for increasing order in the list. Suppose we have an increasing list, then the maximum profit is the list end - list start in this list. 

Suppose we have the increasing list starting from num[j] to num[i-1] and we meet a number, num[i],  which breaks the increasing order, then we gain maximum profit num[i-1] - num[j]. Storting this maximum profit, we continue to find the maximum profit starting
from num[i]. 

One question may be that the maximum profit may be obtained by num[i+k] - num[j], that is, some number after num[i]. Maybe we should continue to search for the maximum profit starting from num[j] even if we meet num[i] > num[j] ? The answer is no. If we
gain the maximum profit for num[j] at num[i+k], since num[i] < num[j], the profit num[i+k] - num[i] > num[i+k] - num[j]. Thus when we meet a number num[i] that breaks the increasing order, we should record the current maximum profit, and start looking for
next maximum profit starting from num[i]. 

Code:

class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty()) return 0;
int maxProfit = 0;
int price = prices[0];
int cost = prices[0];
for(int i = 1; i < prices.size(); i ++){
if(prices[i] >= cost){
price = prices[i];
}else{
cost = prices[i];
price = prices[i];
}
maxProfit = max(maxProfit, price - cost);

}
return maxProfit;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode