题目要求:
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.
这道题的本质在于找出一个数组中任意两个数(序号大的数减去序号小的数)的最大差值。我们发现数组某一段的最大差值信息是可以保存的,并作为下一段的初始数值。具体的递推式如下:
dp[i] = max(dp[i - 1], prices[i] - minPrice);
程序也是比较简单:
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 int sz = prices.size(); 5 if(sz == 0) 6 return 0; 7 8 vector<int> dp(sz, 0); 9 int minPrice = prices[0]; 10 for(int i = 1; i < sz; i++) 11 { 12 dp[i] = max(dp[i - 1], prices[i] - minPrice); 13 if(minPrice > prices[i]) 14 minPrice = prices[i]; 15 } 16 17 return dp[sz - 1]; 18 } 19 };