力扣:“买卖股票的最佳时机“

题目

选自力扣

买卖股票的最佳时机

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

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

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

示例 1:

输入:[7,1,5,3,6,4] 输出:5 解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,
最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

示例 2:

输入:prices = [7,6,4,3,1] 输出:0 解释:在这种情况下, 没有交易完成, 所以最大利润为 0。

提示:

1 < = p r i c e s . l e n g t h < = 1 0 5 1 <= prices.length <= 10^5 1<=prices.length<=105
0 < = p r i c e s [ i ] < = 1 0 4 0 <= prices[i] <= 10^4 0<=prices[i]<=104
在这里插入图片描述

这个问题可以通过一次遍历来解决。我们需要跟踪两个重要的变量:最低价格(minPrice)和最大利润(maxProfit)。随着我们遍历数组,我们将更新这两个变量。

  1. 初始化 minPrice 为正无穷大(或者数组的第一个元素),maxProfit 为 0。
  2. 遍历数组中的每个价格:
    • 如果当前价格比 minPrice 更低,则更新 minPrice
    • 否则,计算当前价格与 minPrice 的差值,并与 maxProfit 比较,如果更大,则更新 maxProfit
  3. 完成遍历后,maxProfit 将包含最大可能的利润。

下面是这个问题的 Java 代码实现:


public class StockProfitCalculator { // 定义类StockProfitCalculator

    public static int maxProfit(int[] prices) { // 定义静态方法maxProfit,参数为整型数组prices,返回值为整型
        if (prices == null || prices.length < 2) { // 检查prices是否为空或长度小于2,如果是则返回0,因为至少需要两天的价格数据才能计算利润
            return 0;
        }

        int minPrice = Integer.MAX_VALUE; // 初始化最小价格为整型最大值,确保任何实际价格都会小于这个值
        int maxProfit = 0; // 初始化最大利润为0

        for (int price : prices) { // 遍历prices数组中的每个价格
            if (price < minPrice) { // 如果当前价格低于已知的最小价格
                minPrice = price; // 更新最小价格为当前价格
            } else { // 否则
                maxProfit = Math.max(maxProfit, price - minPrice); // 计算当前价格和最小价格的差值,如果大于当前最大利润,则更新最大利润
            }
        }

        return maxProfit; // 返回计算得到的最大利润
    }

    public static void main(String[] args) { // 主函数,程序的入口
        int[] example1 = {7, 1, 5, 3, 6, 4}; // 定义一个示例数组example1
        int[] example2 = {7, 6, 4, 3, 1}; // 定义另一个示例数组example2

        System.out.println("Example 1: Max Profit = " + maxProfit(example1)); // 输出example1的最大利润,预期结果为5
        System.out.println("Example 2: Max Profit = " + maxProfit(example2)); // 输出example2的最大利润,预期结果为0,因为价格持续下跌,无法获得正利润
    }
}

测试代码

为了验证上述函数的正确性,我们可以编写一些测试代码:

public static void main(String[] args) {
    int[] example1 = {7, 1, 5, 3, 6, 4};
    int[] example2 = {7, 6, 4, 3, 1};

    System.out.println("Example 1: Max Profit = " + maxProfit(example1)); // Should print 5
    System.out.println("Example 2: Max Profit = " + maxProfit(example2)); // Should print 0
}

这样,我们就有了一个简单且高效的解决方案来计算给定价格数组中的最大利润。

如果我知道以后每天的股票价格,我一定用这个算法来买.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

布说在见

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

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

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

打赏作者

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

抵扣说明:

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

余额充值