leetcode Best Time to Buy and Sell Stock I&&II&&III
I
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size()==0||prices.size()==1)return 0; int min=prices[0]; int max=prices[0]; int diff=0; for(int i=1;i<prices.size();i++) { if(prices[i]<min)min=prices[i]; if(prices[i]-min>diff)diff=prices[i]-min; } return diff; } };
II
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size()==0||prices.size()==1)return 0; int max=prices[prices.size()-1]; int min=prices[prices.size()-1]; int maxprofit=0; for(int i=prices.size()-2;i>=0;i--) { if(prices[i]<min) { min=prices[i]; } else { maxprofit+=max-min; max=min=prices[i]; } } maxprofit+=max-min; return maxprofit; } };
III
class Solution { public: int maxProfit(vector<int> &prices) { int size = prices.size(); if (size == 0) return 0; vector<int> f1(size); vector<int> f2(size); int minV = prices[0]; for (int i = 1; i < size; i++){ minV = std::min(minV, prices[i]); f1[i] = std::max(f1[i-1], prices[i] - minV); } int maxV = prices[size-1]; f2[size-1] = 0; for (int i = size-2; i >= 0; i--){ maxV = std::max(maxV, prices[i]); f2[i] = std::max(f2[i+1], maxV - prices[i]); } int sum = 0; for (int i = 0; i < size; i++) sum = std::max(sum, f1[i] + f2[i]); return sum; } };
对于II,即是求所有递增子序列的和,对于III,用两个数组,一个从前往后加,一个从后往前加,求最大值即可。