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.
Example 1:
Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0.
暴力法,o(n2)可以ac
现在来看如何用dp解决问题
先把问题规模缩小
【7】dp【0】=0;
【7,1】dp【1】=0;
【7,1,5】dp【2】=4这里还不是很容易看出有什么关系,没关系我们看下一个
【7,1,5,3】dp【3】=4我们知道为什么等于4因为dp【2】=4(就是有5-1)那么它大于(3-1)
这里得到dp【i】=Max(dp【i-1】,nums【i】-min)状态转移方程写出来后我们来看
【7,1,5,3,6】dp【4】=5
【7,1,5,3,6,4】dp【5】=5;
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size()<=1) { return 0; } int dp[prices.size()]; for(int i=0;i<prices.size();i++) { dp[i]=0; } int Min=prices[0]; dp[0]=0; int ans=0; for(int i=1;i<prices.size();i++) { if(prices[i]<=Min)Min=prices[i]; dp[i]=max(dp[i-1],prices[i]-Min); ans=max(ans,dp[i]); } return ans; } };