[leetcode] best time to buy and sell stocks III

 Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

不是一个很typical的思路,因为只能有2次transaction,所以。。。从前扫一次,从后面扫一次,分别存在2个buffer里面,然后在扫一次buffer就好啦

  
  
  
  
  1. class Solution { 
  2. public
  3.      
  4.     int maxProfit(vector<int> &prices) { 
  5.         // Start typing your C/C++ solution below 
  6.         // DO NOT write int main() function 
  7.         if(prices.empty()) return 0; 
  8.          
  9.         int minVal = prices[0]; 
  10.         int result = 0; 
  11.          
  12.         vector<int> inOrder; 
  13.         inOrder.push_back(0); 
  14.         vector<int> revOrder; 
  15.         revOrder.assign(prices.size(),0); 
  16.          
  17.         for(int i = 1; i < prices.size(); i++){ 
  18.             if(prices[i] > minVal){ 
  19.                 result = MAX(result, ( prices[i] - minVal)); 
  20.             }else
  21.                 minVal = prices[i]; 
  22.             } 
  23.             inOrder.push_back(result); 
  24.         } 
  25.          
  26.         int maxVal = prices[prices.size()-1]; 
  27.         result = 0; 
  28.          
  29.         for(int i = prices.size()-2; i >= 0; i--){ 
  30.             if(prices[i] < maxVal){ 
  31.                 result = MAX(result, maxVal - prices[i] ); 
  32.             }else
  33.                 maxVal = prices[i]; 
  34.             } 
  35.             revOrder[i] = result; 
  36.         } 
  37.          
  38.          
  39.         result = 0; 
  40.         for (int i = 0; i < inOrder.size()-1; i++) { 
  41.             result = MAX(result, inOrder[i] + revOrder[i+1]); 
  42.         } 
  43.          
  44.         result = MAX(result, revOrder[0]); 
  45.          
  46.         return result; 
  47.          
  48.     } 
  49.      
  50. }; 

 

你可能感兴趣的:(LeetCode)