【LeetCode】121. 买卖业务股票的最佳时机

[复制链接]
发表于 2025-9-25 17:08:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
121. 买卖业务股票的最佳时机

区间内,差值最大,注意并不是最低值和最大值差值就是最大,比方,3,7,1,3,4。差值最大是7-3
解法一: 暴力盘算

遍历全部大概性,记录最大值
空间复杂度:O(n)
时间复杂度:O(n^2)
显然这个时间复杂度是不可担当
  1. public int maxProfit(int[] prices) {
  2.     if (prices == null || prices.length <= 1)
  3.         return 0;
  4.     int n = prices.length;
  5.     int max = 0;
  6.     for (int i = 0; i < n; i++) {
  7.         for (int k = i + 1; k < n; k++) {
  8.             int diff = prices[k] - prices[i];
  9.             if (diff > 0 && diff > max)
  10.                 max = diff;
  11.         }
  12.     }
  13.     return max;
  14. }
复制代码
解法二

股票低买高卖,
假设第一天买进,背面天数买进/卖出

  • 假设买进,代价更低,假设买进min更新当前最少值
  • 假设卖出

    • 当前卖出利润更大,更新最大利润(此时最大利润当前代价 - 之前代价最低点)
    • 当前卖出利润更新,则不更新

  1. public int maxProfit(int[] prices) {
  2.     if (prices == null || prices.length <= 1)
  3.         return 0;
  4.     int min = prices[0], max = 0;
  5.     for (int i = 1; i < prices.length; i++) {
  6.         if (prices[i] < min) {
  7.             min = prices[i];
  8.         } else if (prices[i] - min > max) {
  9.             max = prices[i] - min;
  10.         }
  11.     }
  12.     return max;
  13. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表