Best Time to Buy and Sell Stock

  1. Best Time to Buy and Sell Stock
    有一个price数组,标记第i天交易股票的花费。如果只允许一次交易必须先买后卖,最大收益。

    找price数组中的最小的,然后其后续与其的最大差值为最大收益。

  2. Best Time to Buy and Sell Stock II
    交易任意次数,求整个过程中的最大收益。

    price[i]>price[i-1], 则其差值加入收益中。

  3. Best Time to Buy and Sell Stock with Cooldown
    交易任意多次,但是如果你这次卖了,下次你不能买,只有下下次之后才能买,即中间停一次。
    http://www.cnblogs.com/grandyang/p/4997417.html

 public int maxProfit(int[] prices) {
        int buy = Integer.MIN_VALUE; //为了使第一次不能为buy,则将初始buy变为整数最小值即负数
        int sell = 0, buy1, sell2 = 0;
        for (int i = 0; i < prices.length; i++){
            buy1 = buy;
            buy = Math.max(buy1, sell2 - prices[i]); //此处sell2为sell[i-2]
            sell2 = sell; //此处sell为i-1次的,则在下一次循环中,尚未计算sell前,其相对第i+1为其前2次的,即为sell2
            sell = Math.max(sell, buy1 + prices[i]);
        }
        return sell;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值