leetcode 算法之买卖股票的最佳时机

0 阅读3分钟

给定一个数组 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 <= prices.length <= 105
  • 0 <= prices[i] <= 104

题目分析

我们要注意是我们如果买入了 卖出只能是数组当天买入的下标后面的元素 还有买入的不能大于卖出否则利润就是要返回0 ,我们需要循环去遍历然后判断后面元素是否大于之前然后做差 然后更新最大值 我们也需要定义一个默认最小值 如果后面的小于我们定义的最小值我们需要把我们的小值重新赋值

  • 第一种解法

public int reverse(int[] prices) {
    // 边界条件检查
    if (prices == null || prices.length < 2) {
        return 0;
    }
    int minPrice = prices[0];  // 记录到目前为止的最低买入价格
    int maxProfit = 0;         // 记录最大利润
    
    for (int i = 1; i < prices.length; i++) {
        // 如果当前价格更低,更新最低买入价
        if (prices[i] < minPrice) {
            minPrice = prices[i];
        } else {
            // 计算以当前价格卖出的利润,更新最大利润
            int profit = prices[i] - minPrice;
            if (profit > maxProfit) {
                maxProfit = profit;
            }
        }
    }
    return maxProfit;
}
  • 单元测试

public static void main(String[] args) {
    Leetcode7 solution = new Leetcode7();
    
    // 测试用例1: [7,1,5,3,6,4],期望输出 5 (第2天买入价格1,第5天卖出价格6)
    int[] prices1 = {7, 1, 5, 3, 6, 4};
    System.out.println("测试用例1: " + solution.reverse(prices1));  // 输出: 5
   // System.out.println("测试用例1(简洁写法): " + solution.reverse2(prices1));  // 输出: 5
    
    // 测试用例2: [7,6,4,3,1],价格一直下跌,期望输出 0
    int[] prices2 = {7, 6, 4, 3, 1};
    System.out.println("测试用例2: " + solution.reverse(prices2));  // 输出: 0
}

测试结果

image.png

  • 第二种忙解法

public int reverse2(int[] prices) {
    if (prices == null || prices.length < 2) {
        return 0;
    }
    int minPrice = Integer.MAX_VALUE;
    int maxProfit = 0;
    
    for (int price : prices) {
        minPrice = Math.min(minPrice, price);      // 更新最低买入价
        maxProfit = Math.max(maxProfit, price - minPrice);  // 更新最大利润
    }
    return maxProfit;
}

第二种解放简洁很多 是调用 Math 函数来处理我们最大值利润和和买入最小值的处理代码简洁很多但是没有第一种好理解。

单元测试

public static void main(String[] args) {
    Leetcode7 solution = new Leetcode7();
    
    // 测试用例1: [7,1,5,3,6,4],期望输出 5 (第2天买入价格1,第5天卖出价格6)
    int[] prices1 = {7, 1, 5, 3, 6, 4};
    System.out.println("测试用例1: " + solution.reverse2(prices1));  // 输出: 5
    // 测试用例2: [7,6,4,3,1],价格一直下跌,期望输出 0
    int[] prices2 = {7, 6, 4, 3, 1};
    System.out.println("测试用例2: " + solution.reverse2(prices2));  // 输出: 0
}
  • ####测试结果

image.png