标签:
题目:
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.
解析:
贪心法,分别找到价格最低和最高的一天,低进高出,注意最低的一天要在最高的一天之前。
把原始价格序列变成差分序列,本题也可以做是最大 m 子段和,m = 1。
1 class Solution 2 { 3 public: 4 int maxProfit(vector<int> &prices) 5 { 6 if (prices.size() < 2) return 0; 7 int profit = 0; // 差价,也就是利润 8 int cur_min = prices[0]; // 当前最小 9 for (int i = 1; i < prices.size(); i++) 10 { 11 profit = max(profit, prices[i] - cur_min); 12 cur_min = min(cur_min, prices[i]); 13 } 14 return profit; 15 } 16 };
Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/raichen/p/4932090.html