【LeetCode】股票的最大利润Java题解 |Java刷题打卡

164 阅读1分钟

本文正在参加「Java主题月 - Java 刷题打卡」,详情查看 活动链接

题目描述

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

示例 1:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

  • 买卖股票问题是一类很经典的问题,我们需要认真分析,找出题目的答案。
  • 针对这个题目,分析出首要需要找到价格最小值,然后在价格的相对较高的值的时候卖出,可以得到利润最大值。

AC代码

public class DayCode {
    public static void main(String[] args) {
        int[] prices = new int[]{7, 1, 5, 3, 6, 4};
        int ans = new DayCode().maxProfit(prices);
        System.out.println(ans);
    }

    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int profit = prices[j] - prices[i];
                maxProfit = Math.max(profit, maxProfit);
            }
        }

        return maxProfit;
    }

    public int maxProfit1(int[] prices) {
        int maxProfit = 0;
        int min = Integer.MAX_VALUE;
        for (int price : prices) {
            if (price < min) {
                min = price;
            } else if (price - min > maxProfit) {
                maxProfit = price - min;
            }
        }

        return maxProfit;
    }
}

提交测试

image.png

总结

  • 解法一的时间复杂度是 O(n * n), 空间复杂度是 O(1)
  • 解法二的时间复杂度是 O(n), 空间复杂度是 O(1)
  • 坚持每日一题,加油!