【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:
Date:2018年2月20日
题目地址: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】10.Regular Expression Matching(hard)解题报告
- 【LeetCode】51.N-Queens(hard)解题报告
- 【LeetCode】330.Patching Array(Hard)解题报告
- 【LeetCode】301.Remove Invalid Parentheses(hard)解题报告
- 【LeetCode】321.Create Maximum Number(Hard)解题报告
- 【LeetCode】135.Candy(hard)解题报告
- 【LeetCode】327. Count of Range Sum(Hard)解题报告
- 【LeetCode】297.Serialize and Deserialize Binary Tree(Hard)解题报告
- 【LeetCode】42.Trapping Rain Water(Hard)解题报告
- 【LeetCode】291.Word Pattern II(Hard)解题报告
- 【LeetCode】4.Median of Two Sorted Arrays(Hard)解题报告
- 【LeetCode】52.N-Queens II(hard)解题报告
- 【LeetCode】726.Number of Atoms(Hard)解题报告
- 【LeetCode】282.Expression Add Operators(Hard)解题报告
- 【LeetCode】45.Jump Game II(Hard)解题报告
- 【LeetCode】41. First Missing Positive(Hard)解题报告
- 【LeetCode】403. Frog Jump(Hard)解题报告
- 【LeetCode】164.Maximum Gap(Hard)解题报告
- 【LeetCode】99.Recover Binary Search Tree(Hard)解题报告
- 【LeetCode】664.Strange Printer(hard)解题报告