Best Time to Buy and Sell Stock III -- Leetcode

12.25 2014

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

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int day=prices.size();
        if(day<2) return 0;
        int Max=0;
        int Max1=0;
        int Max2=0;
        int lowest=prices[0];
        for(int i=0;i<day;i++){
            Max1=helper(prices,0,i);
            Max2=helper(prices,i+1,day-1);
            Max=max(Max1+Max2,Max);
        }
        return Max;
    }
    int helper(vector<int> &prices, int start, int end){
        int profit=0;
        int lowest=prices[start];
        for(int i=start;i<=end;i++){
            profit=max(prices[i]-lowest,profit);
            lowest=min(lowest,prices[i]);
        }
        return profit;
    }
};

做法一:拆成两段,对两段分别求最大和,加起来的和取最大值即为答案。但是会出现超时。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int day=prices.size();
        if(day<2) return 0;
        vector<int> v(day,0);
        vector<int> p(day,0);
        for(int i=1, valley=prices[0];i<day;i++){
            valley=min(valley,prices[i]);
            v[i]=max(v[i-1],prices[i]-valley);
        }
        for(int i=day-2, peak=prices[day-1];i>=0;i--){
            peak=max(peak,prices[i]);
            p[i]=max(p[i],peak-prices[i]);
        }
        int profit=0;
        for(int i=0;i<day;i++)
            profit=max(profit,v[i]+p[i]);
        return profit;
    }
};

做法二:

稍微有些不同,主要是在代码上的区别,空间和时间上的tradeoff,把各种可能先算一遍存在vector内然后再进行求最大值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值