122. 买卖股票的最佳时机 II

本文介绍了如何使用贪心算法解决LeetCode 122题——买卖股票的最佳时机II。通过逐日比较价格变化,捕捉价格上涨的差价,实现投资收益最大化。实例代码展示了如何在Java中应用贪心思想求解股票交易问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

122. 买卖股票的最佳时机 II

题解:贪心算法

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码:贪心算法

public class lc_122 {

    public static int maxProfit(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;
    }

    public static void main(String[] args) {
        int prices1[] = {7, 1, 5, 3, 6, 4};
        int profit1 = maxProfit(prices1);
        System.out.println(profit1);

        int prices2[] = {1, 2, 3, 4, 5};
        int profit2 = maxProfit(prices2);
        System.out.println(profit2);

        int prices3[] = {7, 6, 4, 3, 1};
        int profit3 = maxProfit(prices3);
        System.out.println(profit3);
    }
}

参考:

  1. 买卖股票的最佳时机 II
  2. 暴力搜索、贪心算法、动态规划(Java)
  3. 买卖股票的最佳时机 II (贪心,清晰图解)
  4. 买卖股票的最佳时机 II | 贪心 | 最通俗易懂的题解 【c++/java版】
  5. 【贪心】买卖股票的最佳时机II
  6. 一种解法团灭买卖股票问题
  7. 「代码随想录」带你学透股票系列!122. 买卖股票的最佳时机 II【贪心】【动态规划】详解
  8. 简单dp,秒懂股票买卖!🤷‍♀️
  9. 「代码随想录」122. 买卖股票的最佳时机 II【贪心】【动态规划】详解
  10. 122. 买卖股票的最佳时机 II,最简动态规划解法,一看就懂系列~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

dev_zyx

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

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

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

打赏作者

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

抵扣说明:

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

余额充值