【LeetCode】123.Best Time to Buy and Sell Stock III(Hard)解题报告

本文针对LeetCode上的一道经典算法题——最佳买卖股票时机III进行解析,该题允许进行最多两次交易,需找出最大利润。文章提供了一个时间复杂度为O(n),空间复杂度为O(1)的解决方案。

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

【LeetCode】123.Best Time to Buy and Sell Stock III(Hard)解题报告

题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/
题目描述:

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

  仍然不太理解,后续再继续看。

Solution:

/*
        1 2 4 1 5   1415=7
  price  sell2 buy2 sell1 buy1
    1    0      -1     0    -1
    2    1      -1     1    -1
    4    3      -1     3    -1
    1    3       2     3    -1
    5    7       2     4     -1
time : O(n)
space : O(1)
*/
class Solution {
    public int maxProfit(int[] prices) {
        int buy1 = Integer.MIN_VALUE,buy2 = Integer.MIN_VALUE;
        int sell1 = 0 , sell2 = 0;
        for(int price : prices){
            sell2 =  Math.max(sell2 , buy2 + price);
            buy2 = Math.max(buy2 , sell1 - price);
            sell1 = Math.max(sell1 , buy1 + price);
            buy1 = Math.max(buy1 , -price);
        }
        //求最大利润
        return sell2;
    }
}

Date:2018年2月20日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值