买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

public class MaxProfit {
    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4}; // 示例数组
        int maxProfit = maxProfit(prices);
        System.out.println("可以获取的最大利润: " + maxProfit);
    }

    public static int maxProfit(int[] prices) {
        // 如果数组为空或长度为1,则没有交易可进行
        if (prices == null || prices.length < 2) {
            return 0;
        }

        int minPrice = prices[0]; // 最低价格初始化为第一天的价格
        int maxProfit = 0; // 最大利润初始化为0

        for (int i = 1; i < prices.length; i++) {
            // 更新最低价格
            if (prices[i] < minPrice) {
                minPrice = prices[i];
            } else {
                // 计算当前利润
                int currentProfit = prices[i] - minPrice;
                // 更新最大利润
                maxProfit = Math.max(maxProfit, currentProfit);
            }
        }

        return maxProfit;
    }
}

代码解释:

  1. 初始化: 我们设置一个变量 minPrice 来存储遇到的最低价格,并初始化为数组的第一个元素。同时,也初始化一个变量 maxProfit 为 0,用来记录能获得的最大利润。

  2. 遍历价格数组: 从第二天开始(索引 1),依次检查每一天的价格:

    • 如果当前价格小于 minPrice,那么更新 minPrice 为当前价格。
    • 否则,计算当前的利润(当前价格 - minPrice)并查看是否比目前的 maxProfit 更高。如果是,则更新 maxProfit
  3. 返回结果: 遍历结束后,maxProfit 就是能够获得的最大利润。如果没有利润可得,maxProfit 会返回 0。

时间复杂度:

这个算法的时间复杂度是 O(n),其中 n 是数组的长度,因为我们只需要遍历价格数组一次。空间复杂度是 O(1),因为我们只用了一些额外的变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值