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;
}
};