题目描述:
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.
思路:
动态规划
代码:
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 5 int size = prices.size(); 6 if(size == 0 ||size == 1) 7 return 0; 8 int ret = 0; 9 int minPrice = prices[0]; 10 11 for(int i = 1;i<size;i++){ 12 13 if(prices[i] < minPrice)//流式处理,进来先不忙着处理,先判断,再根据判断结果决定要进行的操作 14 minPrice = prices[i]; 15 else 16 { 17 if(prices[i] - minPrice > ret) 18 ret = prices[i] - minPrice; 19 } 20 } 21 22 return ret; 23 24 25 26 27 } 28 };