Stock(买卖股票)

1. 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 (ie, buy one and sell one share of the stock), 
design an algorithm to find the maximum profit.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

记录当前最小的买进价格,随后进行卖出,并且和当前最大的获利相比较,如果比当前最大的还要大,则更新当前最大值,否则继续执行,最后返回最大值。

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <2)
            return 0;
        int max = 0;
        int minprice = prices[0];
        for(int i=0; i<prices.length; i++){
            if(prices[i]-minprice>max){
                max = prices[i]-minprice;
            }
            if(minprice>prices[i]){
                minprice = prices[i];
            }
        }        
        return max;
    }
}

2. 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 (ie, buy 
one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at 
the same time (ie, you must sell the stock before you buy again).

可以无限次买卖股票,但是必须先卖了才能买新的,思路是从第二天开始,如果今日价格比昨天高,那么则可以昨日买入,今日卖出,而到了明日又可以重复该过程直到利润最大值。

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length < 2){
            return 0;
        }
        int sum = 0;
        for(int i=1; i<prices.length; i++){
            if(prices[i-1]<prices[i]){
                sum += prices[i]-prices[i-1];
            }
        }
        return sum;
    }
}

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

第一种方法比较简单,就是当成两个两个stcokI 来求解,,即求[0,i],[i+1,n]两个最大值之和。时间复杂度优化后为O(n)。

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length < 2){
            return 0;
        }
        int[] startprices = new int[prices.length];
        int[] endprices = new int[prices.length];
        for(int i=0; i<prices.length; i++){
            startprices[i] = 0;
            endprices[i] = 0;
        }
        int minprices = prices[0];
        for(int i=1; i<prices.length; i++){
            startprices[i] = Math.max(startprices[i-1], prices[i]-minprices);
            minprices = Math.min(minprices, prices[i]);
        }
        
        int maxprices = prices[prices.length-1];
        for(int i=prices.length-2; i>=0; i--){
            endprices[i] = Math.max(endprices[i+1], maxprices-prices[i]);
            maxprices = Math.max(maxprices, prices[i]);
        }
        
        int max = 0;
        for(int i=0; i<prices.length; i++){
            max = Math.max(max, startprices[i]+endprices[i]);
        }
        return max;
    }
}

4. 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 transactions at the same time (ie, you must sell the stock before you buy again).
**Credits:**Special thanks to [@Freezen](https://oj.leetcode.com/discuss/user/Freezen) for adding this problem and creating all test cases.

这题使用动态规划
我们定义local[i][j]为在到达第i天时最多可进行j次交易并且最后一次交易在最后一天卖出的最大利润,此为局部最优。然后我们定义global[i][j]为在到达第i天时最多可进行j次交易的最大利润,此为全局最优。它们的递推式为:

local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff)

global[i][j] = max(local[i][j], global[i - 1][j])

其中局部最优值是比较前一天并少交易一次的全局最优加上大于0的差值,和前一天的局部最优加上差值中取较大值,而全局最优比较局部最优和前一天的全局最优。
如果k的值远大于prices的天数,比如k是好几百万,而prices的天数就为若干天的话,上面的DP解法就非常的没有效率,应该直接用[Best Time to Buy and Sell Stock II 的方法来求解。

class Solution {
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        if(n<2){
            return 0;
        }
        if(k>=n){
            return maxstock(prices);
        }
        int[][] g = new int[n][k+1];
        int[][] l = new int[n][k+1];
        for(int i=1; i<n;i++){
            int diff = prices[i]-prices[i-1];
            for(int j=1;j<k+1;j++){
                l[i][j] = Math.max(g[i-1][j-1]+Math.max(diff, 0), l[i-1][j]+diff);
                g[i][j] = Math.max(g[i-1][j], l[i][j]);
            }
        }
        return g[n-1][k];
        
    }
    
    public int maxstock(int[] prices){
         if(prices.length < 2){
            return 0;
        }
        int sum = 0;
        for(int i=1; i<prices.length; i++){
            if(prices[i-1]<prices[i]){
                sum += prices[i]-prices[i-1];
            }
        }
        return sum;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容