Java面试经典 150 题.P122. 买卖股票的最佳时机 II(008)

本题来自:力扣-面试经典 150 题

面试经典 150 题 - 学习计划 - 力扣(LeetCode)全球极客挚爱的技术成长平台icon-default.png?t=O83Ahttps://leetcode.cn/studyplan/top-interview-150/

题解:

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

思路如下:

与上一道题不同的是,本题可以多次买入,求总共利润

       1. 遍历数组:

                1.1 当key大于下一个数字的时候,卖出是亏损的,所以直接将key替换为下一个数(在下一天买入)

                1.2 当key小于下一个数字的时候,卖出是赚的,直接卖出,并且再买入(将key替换为下一个数)

        2.返回结果

综上所述:代码可以简写为

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值