这道题尽管是上一道题的增强.可是反而简单了. 能够交易无数次,可是买卖必须成对的出现. 为了简单起见.我用abc三股股票来说明,且忽略掉相等的情况.三个数一共同拥有六种大小关系.注意他们之间的先后顺序是不能乱的. 1. a<b<c. 这样的情况下的最大收益是c-a,c-a=(c-b)+(b-a).连续的大于,依次算差.加起来即可了. 2. b<a<c. 即中间那股小,最大收益是c-b.由于a入b出赔钱,a入c出收益少. 3. a<c<b. 最大收益b-a. 4. b&l…
这道题还是挺难的,属于我前面提到的,给个数组,线性时间找出个什么东西,尽管上面的两个买卖股票也是这类.只是相比之下稚嫩多了.有关至少至多的问题比較烦人,不好想,等再做一些题,可能会发现什么规律.这道题的情况还是比較少的,要么买卖了两次.要么一次. 买卖一次的情况,已经解决过了,如今分析买卖两次的情况. 两次买卖之间是没有交叉的,即下一次买之前一定已经卖掉了.最easy想到,穷去分点,每一个部分都依照买卖一次的方法做. 好,恭喜.你已经走在超时的路上了.那么怎么办呢.有没有一种方法,在线性时间内,…
这样的题就不要去考虑N^2的算法了.肯定会超时的.乍一看,非常可能会想到贪心,可是普通的贪心思路是不行的,比方想找到一个最小值用来买入.尽管它跟最大值之间的差一定是最好的,可是最大值出如今它前面就不行了,找出如今它后面的最大值,仅仅只是是一个局部最优,非常可能前面的最大和次小比他们要好. 所以呢,贪心找的不是两个点,而是差.这种话.每一步都维护一个最小值,然后算跟当前最小之间的差来更新最后的结果. 代码简洁,不在赘述. class Solution { public: int maxProfit…
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 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 as m…
一个系列三道题,我都不会做,google之答案.过了两道,第三道看不懂,放置,稍后继续. 一.Best Time to Buy and Sell Stock I 题目:一个数组表示一支股票的价格变换.要求只买卖一次,获得最大收益. 思路:一开始我认为是寻找最大.最小值,但由于最大值不一定总是出现在最小值的后面,因此WA. 参考思路:DP.对第i个价格,减去前i-1个价格中的最小值(保证该收益是在第i个价格卖出的最大收益),其收益与之前获得的最大收益相比. 代码: public int maxPr…
Best Time to Buy and Sell Stock IV Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You may not engage in multiple…
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 multipl…
Best Time to Buy and Sell Stock II 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 as many transactions as you like (i.e., buy one and sell one s…
Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorith…
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ 题目描述 Say you have an array for which the ith element is the price of a giv…