【贪心算法】Leetcode 122. 买卖股票的最佳时机 II【中等】

买卖股票的最佳时机 II

  • 给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润 。

示例 1:

输入 :prices = [7,1,5,3,6,4]
输出 :7
解释 :在第 2 天(股票价格 = 1)的时候买入,在第 3 天

(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。

随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天

(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。

总利润为 4 + 3 = 7 。

解题思路

这是一个典型的贪心算法问题。

  • 可以贪心地选择每次股票价格下跌之前卖出,上涨之前买入。
  • 因此,只需计算所有相邻价格之间的差价,且如果差价大于 0, 则将其累加到最大利润中。

java实现

java 复制代码
public class BestTimeToBuyAndSellStockII {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            int profit = prices[i] - prices[i - 1];
            if (profit > 0) {
                maxProfit += profit;
            }
        }
        return maxProfit;
    }

    public static void main(String[] args) {
        BestTimeToBuyAndSellStockII maxProfit = new BestTimeToBuyAndSellStockII();
        int[] prices1 = {7, 1, 5, 3, 6, 4};
        int result1 = maxProfit.maxProfit(prices1);
        System.out.println("Test Case 1:");
        System.out.println("Prices: [7, 1, 5, 3, 6, 4]");
        System.out.println("Max Profit: " + result1); // Expected: 7

        int[] prices2 = {1, 2, 3, 4, 5};
        int result2 = maxProfit.maxProfit(prices2);
        System.out.println("\nTest Case 2:");
        System.out.println("Prices: [1, 2, 3, 4, 5]");
        System.out.println("Max Profit: " + result2); // Expected: 4

        int[] prices3 = {7, 6, 4, 3, 1};
        int result3 = maxProfit.maxProfit(prices3);
        System.out.println("\nTest Case 3:");
        System.out.println("Prices: [7, 6, 4, 3, 1]");
        System.out.println("Max Profit: " + result3); // Expected: 0
    }
}

时间空间复杂度

  • 时间复杂度: 遍历一次股票价格数组,时间复杂度为 O(n),其中 n 是数组的长度。
  • 空间复杂度: 使用了常数级的额外空间,空间复杂度为 O(1)。
相关推荐
DoraBigHead39 分钟前
小哆啦解题记——异位词界的社交网络
算法
木头左2 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
web_Hsir8 小时前
vue3.2 前端动态分页算法
前端·算法
地平线开发者10 小时前
征程 6M 部署 Omnidet 感知模型
算法·自动驾驶
秋说11 小时前
【PTA数据结构 | C语言版】线性表循环右移
c语言·数据结构·算法
浩瀚星辰202411 小时前
图论基础算法:DFS、BFS、并查集与拓扑排序的Java实现
java·算法·深度优先·图论
JiaJZhong13 小时前
力扣.最长回文子串(c++)
java·c++·leetcode
oioihoii14 小时前
C++随机打乱函数:简化源码与原理深度剖析
开发语言·c++·算法
不知名。。。。。。。。14 小时前
分治算法---快排
算法