`
frank-liu
  • 浏览: 1666086 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

leetcode: Best Time to Buy and Sell Stock III

 
阅读更多

问题描述:

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).

原问题链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

 

问题分析

  这个问题里和前面的问题有不一样的地方, 在之前的问题里主要是针对一个时间段的价格变化做一次交易,那么我们的实现里只需要找到当前值和之前最小值之间的差,并取出其中最大的那个就可以了。但是这里的情况稍微不同,因为它这里是可以最多可以交易两次。也就是说,为了获取到这个最大值,我们可以交易一次,也可以交易两次。

  那么,在实际的价格变化曲线里,可能有很多种情况。可能在序列里只有一个递增的情况,比如序列: 10, 9, 8, 20。这个时候我们能取得的最大的价值就是20 - 8。也就是说这里只需要一次交易就可以得到最理想的结果。也可能有多个变化的序列,比如说5, 6, 4, 8。这个时候我们取6 -5,再加上8 - 4这两次交易的结果,可以得到最佳结果。所以说,上面这个问题的难点就在于怎么去选择和利用好这最多两次的交易。

  要解决这个问题,有一个需要利用的地方。就是如果我们最坏的情况是要两次交易的话,该怎么把之前一次的交易给保存起来以方便比较呢?在之前只允许一次交易的问题解决方案中,其实给了我们一个思路。这个思路是每次取到当前位置为止最小的元素,再将当前元素和这个最小值相减,再通过和之前这些差值的最大进行比较,取出最大的这个作为到当前这个位置一次交易所能获得的最大利益。那么,在实现的时候,我们可以声明一个和价格数组一样长度的列表,记录每次访问到当前位置所能取得的最大利益。这部分的实现如下:

 

        int len = prices.length, result = 0;
        int low = prices[0], high = prices[len - 1];
        int[] profitsHistory = new int[len];
        for(int i = 0; i < len; i++) {
            low = Math.min(low, prices[i]);
            result = Math.max(result, prices[i] - low);
            profitsHistory[i] = result;
        }

  现在,剩下的部分就是怎么去比较和找最大的利益值了。我们从prices列表的最后往前,每次比较和取当前最大的价格值,再用这个值减去当前值,这个时候取得的值相当于是从最后到当前元素所能取得的最大利益值,在把这个值加上当前profitsHistory[i] 的,就是我们最多交易两次可能取得的最大值了。每次我们取它们中间最大的值保存起来。这样我们就能找到最多交易两次所能得到的最大值。

  详细的代码实现如下:

 

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length < 2) return 0;
        int len = prices.length, result = 0;
        int low = prices[0], high = prices[len - 1];
        int[] profitsHistory = new int[len];
        for(int i = 0; i < len; i++) {
            low = Math.min(low, prices[i]);
            result = Math.max(result, prices[i] - low);
            profitsHistory[i] = result;
        }
        for(int i = len - 1; i >= 0; i--) {
            high = Math.max(high, prices[i]);
            result = Math.max(result, high - prices[i] + profitsHistory[i]);
        }
        return result;
    }
}
分享到:
评论

相关推荐

    leetcode题目:Best Time to Buy and Sell Stock II

    leetcode题目:Best Time to Buy and Sell Stock II

    lrucacheleetcode-LeetCode:CppSourceCode的LeetCode解决方案

    leetcode LeetCode 解决题目的总数: 136/1753 微信公众号: 工程师Ruojhen 算法-动态规划 题号 名称 English Name 题解 53 最大子序和 Maximum Subarray 70 爬楼梯 Climbing Stairs 121 买卖股票的最佳时机 Best Time...

    股票收益leetcode-leetcode:leetcode摘要

    股票收益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) ...

    javalruleetcode-leetcode-java:力码笔记

    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分类-LeetCode:力码

    leetcode 分类 LeetCode LeetCode Java Solution 2018年5月31日 更新 最近刷了一遍 LeetCode,发现第一次的代码确实有些 low 很多代码并不简洁,本来1行的代码可以写成3行 思维混乱 没有按照题目类型分类 没有写结题...

    LeetCode:LeetCode Java解决方案

    公众号 coding 笔记、点滴记录,以后的文章也会...最近花时间分门别类整理了 LeetCode 的前 500 题,把相似的题目都放在了一起,比如Best Time to Buy and Sell Stock的6道题,这些题目放在一起刷效果更好。 简书博客:

    leetcode卡-leetcode:利特码解决方案

    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 ...

    Andy619-Zhu#CS-Notes-chu#63. 股票的最大利润1

    63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必

    leetcode-leetcode:leetcode的最佳C++解决方案

    leetcode leetcode The optimum C++ solutions for the leetcode 这是我自己写的leetcode的题解,目前已经完成了70%左右,后续部分会很快更新 这里放上来的代码都能保证是最优解(复杂度最优) 当然有些题目因为测试...

    LeetCode:Leetcode-解决方案

    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小岛出水口-leetcode:leetcode训练

    leetcode小岛出水口 leetcode training one problem on file 为了方便文档管理,项目逐渐文档化,以单个文件作为集合最小集。 go语言不能完全适合写算法题 后续会尽可能加入rust或者c的题解 清单 0965. Univalued ...

    LeetCode:LeetCode题解

    Best_Time_To_Buy_And_Sell_Stock Java 简单的 122 Best_Time_To_Buy_And_Sell_StockII Java 简单的 125 Valid_Palindrome Java 简单的 136 单号 Java 简单的 137 Single_NumberII Java 中等的 167 Two_...

    leetcode中文版-leetcode:leetcode

    leetcode中文版车鸟 一组用python编写的算法。 种类 ...best_time_to_buy_and_sell_stock_II binary_tree_inorder_traversal binary_tree_level_order_traversal binary_tree_level_order_traversal_I

    javalruleetcode-leetcode:更多信息请访问Gitbook:https://wentao-shao.gitbook.io/

    Best Time To Buy And Sell Stock [Binary Tree](Basic-Knowledge/Binary tree.md) Serialize And Deserialize Bit 1.position 2.sequence Sell Stock 区间型 矩阵坐标 Word Ladder Add Two Numbers Matrix Spiral ...

    股票买卖最佳时机leetcode-best-time-to-buy-and-sell-stock:让我们弄清楚什么时候买一些股票!这不应该在现

    股票买卖最佳时机leetcode GitFitCode 配对编码挑战! 买卖股票的最佳时机 让我们弄清楚什么时候买一些股票! 这不应该在现实生活中使用。 现在不管你认为你的算法有多好:)。 我确实鼓励您选择一只您感兴趣的股票,...

    Leetcode的ac是什么意思-LeetCodeInJava:leetcode-java

    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 ...

    cpp-算法精粹

    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 ...

    leetcode答案-LeetCode-Trip:LeetCode刷题代码,大佬勿入

    leetcode 答案 LeetCode-Trip LeetCode刷题代码,大佬勿入。 为一年后的研究生找工作准备 目标是BAT的算法岗哈哈哈哈哈 争取做到每日一更 嗯…… 19.10.22:鸽了这么久,我又回来了……主要在实验室天天没啥事,过于...

    leetcode浇花-LCSolutions:我的力扣解决方案

    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...

    LeetCode最全代码

    260 | [Single Number III](https://leetcode.com/problems/single-number-iii/) | [C++](./C++/single-number-iii.cpp) [Python](./Python/single-number-iii.py) | _O(n)_ | _O(1)_ | Medium || 268| [Missing ...

Global site tag (gtag.js) - Google Analytics