[Java][Leetcode middle] 122. 买卖股票的最佳时机 II

方法一,自己想的

本题中可以多次买入股票,那么:

  1. 如果第二天股票涨了并且还没有买入:选择买入,因为一定可以盈利(可能是明天卖,也可能是未来某一天价格更高的时候卖)
  2. 如果第二天股票跌了并且已经买入了:选择卖出(今天卖了之后可以拿明天低成本的筹码,最差的情况就是明天当天卖当天买,起码不会亏钱)
public int maxProfit(int[] prices) {
        int len = prices.length;
        int profit = 0;

        int buyFlag = 0;
        int buyPrice = 0;
        int salePrice = 0;

        for (int i = 0; i < len-1; i++) {
            if (buyFlag == 0) {
                if (prices[i] < prices[i + 1]) {
                    // 第二天价格涨了
                     buyPrice = prices[i]; // 有盈利空间,买入
                     buyFlag = 1;
                 }
             }else{
                if (prices[i] > prices[i + 1]) {
                    // 明天降价了,今天卖出
                    salePrice = prices[i];
                    profit = profit + salePrice - buyPrice;
                    buyFlag = 0;
                }
             }
        }

        // 手中还有股票没有卖出
        if(buyFlag==1 && prices[len-1] > buyPrice){
            profit = profit + prices[len-1] - buyPrice;
        }

        return profit;
    }

方法二

由于没有手续费以及不限制交易次数,所以只要比昨天价格高今天就进行买入卖出,这样就可以把所有利润收入囊中

    public int maxProfit222(int[] prices) {
        // 由于不限制交易次数,所以比昨天价格高今天进行买入卖出,这样就可以把所有利润收入囊中
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i-1]) {
                res += prices[i] - prices[i-1];
            }
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小雅痞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值