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;
}
}
6968




被折叠的 条评论
为什么被折叠?



