这道题尽管是上一道题的增强.可是反而简单了. 能够交易无数次,可是买卖必须成对的出现. 为了简单起见.我用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…
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…
一天一道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…
转载请注明出处:z_zhaojun的博客 原文地址 题目地址 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 lik…
Problem Link: http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ We solve this problem using Greedy Algorithm, which only scan the prices list once. The worst-case running time is O(n). According to the problem description, we know t…
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/#/description 题目描述 Say you have an array for which the ith element is the price of a given stock on day…
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 (ie, buy one and sell one share of the stock multiple times). Ho…
题目: 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 (ie, buy one and sell one share of the stock multiple times)…