买卖股票的最佳时机(只能有一次买卖,可以最多两次买卖,不限次数)

算法题:买卖股票的最佳时机(只能有一次买卖,可以最多两次买卖,不限次数)

LeetCode——Best Time to Buy and Sell Stock III

 

package src.main.java;

public class test {

//买卖一次
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length==0)
            return 0;
        int local = 0;
        int global = 0;

        for(int i=0;i<prices.length-1;i++)
        {
            //计算两天股票的差。
            int diff = prices[i+1]-prices[i];
            // 计算局部最大涨幅。在local+diff与0中取最大值其目的是:出现大跌,即local+diff为负,
            // 此时如果直接赋值给local会出现local为负的情况,股票再涨的时候local+diff计算的就不是计算涨幅了。
            local = Math.max(local+diff,0);
            //记录股票全局最大涨幅
            global = Math.max(local, global);
        }
        return global;
    }

//不限次数
    public int maxProfit_II(int[] prices) {

        if (prices == null || prices.length == 0)
            return 0;
        int res = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            //计算两天股票的差。
            int diff = prices[i + 1] - prices[i];
            //凡是两天股票差大于零的情况,都买入。
            if (diff > 0)
                res += diff;
        }
        return res;
    }

//可以最多两次买卖;或者买卖K次
    public int maxProfit_III(int[] prices) {
        if(prices==null || prices.length==0)
            return 0;
        int[] local = new int[3];
        int[] global = new int[3];
        for(int i=0;i<prices.length-1;i++)
        {
            int diff = prices[i+1]-prices[i];
            for(int j=2;j>=1;j--)
            {
                local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);
                global[j] = Math.max(local[j],global[j]);
            }
        }
        return global[2];
    }



    public static void main (String[] arg){
        test test = new test();

        int prices [] = {1,3,5,7,9,-10,-22,-35};

        System.out.println(test.maxProfit(prices));

    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值