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

【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,Array)