标签:
题目的意思是整个过程中只能买一只股票然后卖出,也可以不买股票。也就是我们要找到一对最低价和最高价,最低价在最高价前面,以最低价买入股票,以最低价卖出股票。
分析一:扫描一遍,找到最大增长即可。从前往后,用当前价格减去此前最低价格,就是在当前点卖出股票能获得的最高利润。扫描的过程中更新最大利润和最低价格就行了。算法复杂度O(n)。
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 int maxp = 0; 5 int profit = 0; 6 int days = prices.size(); 7 if (days <= 0) 8 return 0; 9 int low = prices[0]; 10 for (int i = 1; i < days; i++) 11 { 12 profit = prices[i]-low; 13 if (profit > maxp) maxp = profit; 14 if (prices[i] < low) low = prices[i]; 15 } 16 return maxp; 17 } 18 };
分析二:按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2]。求新数组的最大子段和就是我们求得最大利润,假设最大子段和是从新数组第 i 到第 j 项,那么子段和= prices[j]-prices[j-1]+prices[j-1]-prices[j-2]+...+prices[i]-prices[i-1] = prices[j]-prices[i-1], 即prices[j]是最大价格,prices[i-1]是最小价格,且他们满足前后顺序关系。代码如下:
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 int n = prices.size(); 5 if (n <= 1) 6 return 0; 7 int res = 0; 8 int currsum = 0; 9 for (int i = 1; i < n; i++) 10 { 11 if (currsum <= 0) 12 currsum = prices[i]-prices[i-1]; 13 else 14 currsum += prices[i]-prices[i-1]; 15 if (currsum > res) 16 res = currsum; 17 } 18 return res; 19 } 20 };
LeetCode - Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/bournet/p/4338174.html