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.
思路:变相的求最大子数组,是算法导论上的例题,书上用分治法做的。
若prices=[1,4,2,8,1],每两数相减所得的利润,即头一天买入,第二天卖出。
profit=[0,3,-2,6,-7],可以看到第一天买入,最后一天卖出的profit为3+(-2)+6+(-7)=0
代码:
class Solution { public: int maxProfit(vector<int> &prices) { int len=prices.size(); int res=0; int temp=0; if(len==0) return res; vector<int> profit(len,0); vector<int> dp(len,0); for(int i=0;i<len;++i){ if(i==0) {profit[i]=0;continue;} profit[i]=prices[i]-prices[i-1]; } dp[0]=profit[0]; for(int i=1;i<len;++i){ dp[i]=max(dp[i-1]+profit[i],profit[i]); if(dp[i]>res) res=dp[i]; } return res; } };