码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock III

时间:2014-08-14 23:19:46      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   使用   os   io   strong   

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).

思路:使用动态规划的思想:分别从前往后和从后往前遍历数组,找出A[0]-A[i]和A[i]-A[n]区间内的最大利润。然后,再次遍历数组便能找出前一部分利润和后一部分利润加和最大的利润值。时间复杂度为O(n)。

 1 class Solution {
 2 public:
 3     int maxProfit( vector<int> &prices ) {
 4         int size = prices.size();
 5         if( size <= 1 ) { return 0; }
 6         vector<int> invMaxProfit( size, 0 );
 7         int curMax = prices[size-1];
 8         for( int i = size-2; i >= 0; --i ) {
 9             if( curMax <= prices[i] ) {
10                 curMax = prices[i];
11             } else {
12                 invMaxProfit[i] = curMax - prices[i];
13             }
14         }
15         int curMin = prices[0], profit = 0, totalProfit = invMaxProfit[0];
16         for( int i = 0; i < size-1; ++i ) {
17             if( curMin > prices[i] ) { curMin = prices[i]; }
18             if( profit < prices[i] - curMin ) { profit = prices[i] - curMin; }
19             if( totalProfit < profit + invMaxProfit[i+1] ) { totalProfit = profit + invMaxProfit[i+1]; }
20         }
21         return totalProfit;
22     }
23 };

 

Best Time to Buy and Sell Stock III,布布扣,bubuko.com

Best Time to Buy and Sell Stock III

标签:des   style   blog   color   使用   os   io   strong   

原文地址:http://www.cnblogs.com/moderate-fish/p/3913305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!