Leetcode 123. Best Time to Buy and Sell Stock III 股票买卖3 解题报告

1 解题思想

嗯,是的,已经第三题了,数组代表什么我不想再复述一次,自己看:
Leetcode 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告
Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告

这道题的难点或者说同点在于:
只允许买卖两次

这道题本质上用的是第一题的方法,我也看了下Discuss,用的也基本一样。

所谓用第一套题是什么意思,是什么动态规划思想?其实就是用两次题目1中的方式,但是第二次买卖需要加上当前第一次利润的状态?

不信 你看代码就知道

2 原题

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

3 AC解

public class Solution {
    public int maxProfit(int[] prices) {
        /**
         * 同Discuss的主流经典高效解法,相当于第一题的加强版
         * 初始状态
         * */
        int buy1 = Integer.MIN_VALUE,sell1 = 0;
        int buy2 = Integer.MIN_VALUE,sell2 = 0;
        for(int price : prices){
            // 第一次购买
            if ( buy1 < -price) buy1 = -price;
            // 第一次卖出去的可能的最大利润
            if ( sell1 < buy1 + price ) sell1 = buy1 + price;
            //注意第二次的利润已经包含第一次的了
            //同理,第二次购买,注意这里是
            if ( buy2 < sell1 - price) buy2 = sell1 - price;
            //最后一次
            if ( sell2 < buy2 + price ) sell2 = buy2 + price;
        }
        return sell2;
    }
}

3 AC解

public class Solution {
    public int maxProfit(int[] prices) {
        /**
         * 同Discuss的主流经典高效解法,相当于第一题的加强版
         * 初始状态
         * */
        int buy1 = Integer.MIN_VALUE,sell1 = 0;
        int buy2 = Integer.MIN_VALUE,sell2 = 0;
        for(int price : prices){
            // 第一次购买,始终买当前所有里面最便宜的那一次,第一次买,利润肯定为负,但是要找出最少的那一个
             if ( buy1 < -price) buy1 = -price;
            // 第一次卖出去的可能的最大利润,到这里都原理同第一题
            if ( sell1 < buy1 + price ) sell1 = buy1 + price;
            //注意第二次的利润已经包含第一次的了,这也是唯一一个不一样的难点
            //同理,第二次购买,但是注意这里有个状态的加成 sell1
            if ( buy2 < sell1 - price) buy2 = sell1 - price;
            //最后一次
             if ( sell2 < buy2 + price ) sell2 = buy2 + price;
        }
        return sell2;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值