【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III

本博客探讨了一个算法问题,目标是在给定的股票价格数组中找到最大利润,限制为最多进行两次交易。通过定义两个数组分别记录从左到右和从右到左的最大利润,最终遍历整个数组,计算每一步的最大可能利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。你最多可以完成两笔交易。

样例
给出一个样例数组 [4,4,6,1,1,4,2,5], 返回 6

注意
你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)

class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        if(null == prices || prices.length < 2)return 0;
        int[] profitLeft =  new int[prices.length];
        int[] profitRight = new int[prices.length];

        int minPrice = prices[0];
        for(int i = 1; i < prices.length; i++) {
            profitLeft[i] = Math.max(profitLeft[i - 1], prices[i] - minPrice);
            minPrice = Math.min(minPrice, prices[i]);
        }

        int maxPrice = prices[prices.length - 1];
        for(int i = prices.length - 2; i >= 0; i--) {
            profitRight[i] = Math.max(profitRight[i + 1], maxPrice - prices[i]);
            maxPrice = Math.max(maxPrice, prices[i]);
        }

        int result = 0;
        for(int i = 0; i < prices.length; i++) {
            result = Math.max(result, profitLeft[i] + profitRight[i]);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值