【LeetCode】121.Best Time to Buy and Sell Stock
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.
题目分析:
做的时候,想用动态规划做,当时写不出比较好表达地递推式。因为最大值和最小值有一个前后关系:某一时刻最大值定下来后,想再移动最小值,则此时最大值也要改变,若只要改变最大值,最小值不受影响。这样子比较会比较混乱。
改变思路:从后往前遍历,到下标i时,则表示第i天买入,这样赚到的最大利润是i+1天~n-1填最大股价减去第i天的。
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 //if (0 == prices.size()) return 0; 5 int length = prices.size(); 6 int result = 0; 7 int maxPrice = result; 8 for (int i = length - 1; i >= 0; --i) 9 { 10 maxPrice = max(maxPrice, prices[i]); 11 result = max(result, maxPrice - prices[i]); 12 } 13 return result; 14 } 15 };
198 / 198 test cases passed.
|
Status:
Accepted |
Runtime: 11 ms
|
Submitted: 0 minutes ago
|