首页 > 其他 > 详细

Best Time to Buy and Sell Stock III

时间:2014-04-12 02:57:23      阅读:586      评论:0      收藏:0      [点我收藏+]

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

可以买两次。

如果只是两次,确实很好做。两个数组记录该点前最大利润和该点后的最大利润,然后找出利润和最大的点便可。log n。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        vector<int> before(n,0);
        vector<int> after(n,0);
         
        for(int i = 1 ; i < n ;i++)
        {
            if(prices[i]-prices[i-1]+before[i-1]>0)
            before[i]= prices[i]-prices[i-1]+before[i-1];
            else
            before[i] = 0;
        }
        for(int i = n-2 ; i >= 0 ;i--)
        {
            if(prices[i+1] -prices[i] + after[i+1] > 0 )
            after[i] = prices[i+1] -prices[i] + after[i+1];
            else
            after[i] = 0;
        }
        int max =0;
        for(int i = 1; i < n ; i++)
        {
            if(before[i]<before[i-1])before[i]=before[i-1];
        }
        for(int i= n-2;i>=0;i--)
        {
            if(after[i]<after[i+1])after[i]=after[i+1];
        }
        for(int i = 0 ; i < n ; i++)
        {
            if(before[i] + after[i] > max)
            max = before[i] + after[i];
        }
        return max;
         
         
    }
};

  

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

Best Time to Buy and Sell Stock III

原文:http://www.cnblogs.com/pengyu2003/p/3659413.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!