121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description

股票买入和卖出的最大差价,只允许交易一次,实际上就是计算数组中靠后的值和靠前的值最大差。

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



看了一下讨论区,题目可以变形成,如果input是前后两个数字的差,比如输入由{1, 7, 4, 11}变成{0, 6, -3, 7},这道题就转换成maximum subarray(第53题).

逻辑上,题目的思路就变成了,求由前后两个数字差形成的新数组的最大子数列和。如果这个和小于0,则返回0.

public int maxProfit(int[] prices) {
        int maxCur = 0, maxSoFar = 0;
        for(int i = 1; i < prices.length; i++) {
            maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
            maxSoFar = Math.max(maxCur, maxSoFar);
        }
        return maxSoFar;
    }
maxCur:最大值;maxSoFar:当前最大值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值