[LeetCode] Best Time to Buy and Sell Stock 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).

思路:因为要交易两笔,所以可以定位下标i,在i左边为第一笔交易的最大值p1[i],i右边为第二笔交易的最大值p2[i],因此可以把题目转换为求p1[i]和p2[i]的和的最大值。

          分三步走,第一步:求p1[i]从左往右算

                            第二步:求p2[i]从右往左算

                            第三步:变量i,求p1[i] +p2[i]的最大值

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int ans = 0,len = prices.size();
        if(len == 0) return 0;
        int p1[len],p2[len];
        memset(p1,0,sizeof(int)*len);
        memset(p2,0,sizeof(int)*len);
        int min = prices[0];
        for(int i = 1;i < len;i ++){
            p1[i] = prices[i] - min > p1[i - 1] ? prices[i] - min : p1[i - 1];
            min = prices[i] < min ? prices[i] : min;
        }
        int max = prices[len - 1];
        for(int i = len - 2;i >= 0;i --){
            p2[i] = max - prices[i] > p2[i + 1] ? max - prices[i] : p2[i + 1];
            max = prices[i] > max ? prices[i] : max;
        }
        ans = p1[0] + p2[0];
        for(int i = 1;i < len;i ++)
            ans = ans > p1[i] + p2[i] ? ans : p1[i] + p2[i];
        return ans;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值