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).
[balabala] 自己的想法是先找出收益最大的一笔收益,然后从剩余区间中寻找次大的收益,但是在一些case上会失败,比如 [6,1,3,2,4,7]。为什么这种贪婪做法得不到全局最优解呢?如yb君指点,因为第一次交易确定会影响第二次交易的可选范围,子问题之间相互影响,所以不可用最优子问题叠加获取最优解。
正确的思路:至多能做两笔交易,而且交易之间没有重叠,想到可以用divide and conque. 如yb君说,需要综合使用多种算法的题目就会显得比较难。这题就是分治 + 动归 综合题。
public class Solution { // 以每一天为分界点,分别求出左边和右边能获得的最大收益,然后求出最大值 // 分治 + 动归 public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; int[] left = new int[prices.length]; int low = prices[0]; int maxleft = 0; for (int i = 0; i < prices.length; i++) { left[i] = Math.max(maxleft, prices[i] - low); low = Math.min(low, prices[i]); } int[] right = new int[prices.length]; int high = prices[prices.length - 1]; int maxright = 0; for (int i = prices.length - 1; i >=0 ;i--) { right[i] = Math.max(maxright, high - prices[i]); high = Math.max(high, prices[i]); } int maxprofit = 0; for (int i = 0; i < prices.length; i++) { maxprofit = Math.max(maxprofit, left[i] + right[i]); } } ////////////////////////////////下面为不正确思路的实现////////////////////////////// //fail @ [6,1,3,2,4,7] class ProfitInfo { int buyDay; int sellDay; int profit; public ProfitInfo(int buyDay, int sellDay, int profit) { this.buyDay = buyDay; this.sellDay = sellDay; this.profit = profit; } } public int maxProfit(int[] prices) { if (prices == null || prices.length < 2) return 0; ProfitInfo profit1 = maxProfit(prices, 0, prices.length - 1); ProfitInfo profit2 = maxProfit(prices, 0, profit1.buyDay - 1); ProfitInfo profit3 = maxProfit(prices, profit1.sellDay + 1, prices.length - 1); return profit1.profit + Math.max(profit2.profit, profit3.profit); } private ProfitInfo maxProfit(int[] prices, int start, int end) { if (start >= end) // length of range <= 1 return new ProfitInfo(start, end, 0); int min = start; int buy = start; int profit = 0; int sell = start; for (int i = start + 1; i <= end; i++) { if (prices[i] < prices[min]) { min = i; } else if (prices[i] > prices[min]){ int currProfit = prices[i] - prices[min]; if (currProfit >= profit) { profit = currProfit; buy = min; sell = i; } } } return new ProfitInfo(buy, sell, profit); } // fail @ [2, 4, 1] buy不能同时承担最小价格日以及当前最大profit的购买日,两者不一定是同一个值 private ProfitInfo maxProfit(int[] prices, int start, int end) { if (start >= end) // length of range <= 1 return new ProfitInfo(start, end, 0); int buy = start; int profit = 0; int sell = start; for (int i = start + 1; i <= end; i++) { if (prices[i] < prices[buy]) { buy = i; } else if (prices[i] > prices[buy]){ int currProfit = prices[i] - prices[buy]; if (currProfit >= profit) { profit = currProfit; sell = i; } } } return new ProfitInfo(buy, sell, profit); } }
相关推荐
leetcode题目:Best Time to Buy and Sell Stock II
java lru leetcode leetcode-java leetcode刷题笔记 ...III 141.Linked List Cycle 142.Linked List Cycle II 188.Best Time to Buy and Sell Stock IV 217.Contains Duplicate 263.Ugly Number 264.Ugly Number II
股票买卖最佳时机leetcode GitFitCode 配对编码挑战! 买卖股票的最佳时机 让我们弄清楚什么时候买一些股票! 这不应该在现实生活中使用。 现在不管你认为你的算法有多好:)。 我确实鼓励您选择一只您感兴趣的股票,...
leetcode leetcode The optimum C++ solutions for the leetcode 这是我自己写的leetcode的题解,目前已经完成了70%左右,后续部分会很快更新 这里放上来的代码都能保证是最优解(复杂度最优) 当然有些题目因为测试...
股票收益leetcode LeetCode 股票问题 Best Time to Buy and Sell Stock (Easy) 一次交易,找最大收益 for i in prices: low = min(low, i) profit = max(profit, i-low) Best Time to Buy and Sell Stock II (Easy) ...
leetcode LeetCode 解决题目的总数: 136/1753 微信公众号: 工程师Ruojhen 算法-动态规划 题号 名称 English Name 题解 53 最大子序和 Maximum Subarray 70 爬楼梯 Climbing Stairs 121 买卖股票的最佳时机 Best Time...
leetcode 答案 LeetCode-Trip LeetCode刷题代码,大佬勿入。 为一年后的研究生找工作准备 目标是BAT的算法岗哈哈哈哈哈 争取做到每日一更 嗯…… 19.10.22:鸽了这么久,我又回来了……主要在实验室天天没啥事,过于...
leetcode 浇花力扣解决方案 简单的 #0001 - Two Sum #0007 - Reverse Integer #0009 - Palindrome Number #0035 - Search Insert Position #0058 - Length of Last Word #0066 - Plus One #0083 - Remove Duplicates...
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/ * * 思路: * 股票只能买卖一次 T+1 操作 * 最大利润 = 最高点 - 最低点 * 并且 最高点只能在 最低点的后面 * * */ public int maxProfit_1(int...
Best Time to Buy and Sell Stock [121]3. Climbing Stairs [70]4. Maximum Subarray [53]5. House Robber [198]6. Range Sum Query - Immutable [303]7. Counting Bits [338]8. Palindromic Substrings [647]9. ...
Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...
圆和椭圆重叠leetcode ——#158 尖端 关心特殊情况 从不同的方向思考 简单的 大批 1.Two Sum -> 使用哈希表避免遍历列表448.查找数组中消失的所有数字-> 1.建立缓冲区来计算数字| 2.使用数组作为带符号的缓冲区118....
leetcode 分类 LeetCode LeetCode Java Solution 2018年5月31日 更新 最近刷了一遍 LeetCode,发现第一次的代码确实有些 low 很多代码并不简洁,本来1行的代码可以写成3行 思维混乱 没有按照题目类型分类 没有写结题...
leetcode 第三题 java 介绍 欢迎!..."https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/", "beats": 0.9000, "category": ["dynamic-programming"], "tags": ["your-wh
201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _...
股票买卖最佳时机leetcode 股票利润最大化 描述 该项目在 localhost:8080 上公开了一个 REST URL,它接受具有 NASDAQ 股票代码的 JSON 编码查询。 它返回一个 JSON 响应,其中包含过去 180 天内最大利润的买入和卖出...
股票买卖最佳时机leetcode 使用机器学习进行纳斯达克 100 股票预测分析 目录 描述 此 Web 应用程序通过 Scikit-Learn 使用前 6 个月的历史价格教机器学习,从而实现机器学习以预测历史预测。该应用程序通过 AWS 部署...
leetcode卡 leetcode exercises 3-5 solutions everyday. fighting~ TODO array Best Time to Buy and Sell Stock II Valid Sudoku linked list Palindrome linked list Linked List Cycle trees Convert Sorted ...
63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必
Best Time to Buy and Sell Stock III Best Time to Buy and Sell Stock IV Best Time to Buy and Sell Stock with Cooldown Interleaving String Scramble String Minimum Path Sum Edit Distance Decode Ways ...