您的位置:首页 > 其它

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

2018-02-20 17:28 465 查看
【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日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode