Best Time to Buy and Sell Stock

只能买1次的股票问题

思路:遍历数组的同时,记录到当前天为止的历史最低价格,那么在当前天卖出的最大收益就是当前价格减去历史最低价格,同时更新历史最大收益。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices == null || prices.length == 0) {
 4             return 0;
 5         }
 6         int min_price = Integer.MAX_VALUE;
 7         int max_profile = 0;
 8         
 9         for (int i : prices) {
10             min_price = Math.min(min_price, i);
11             max_profile = Math.max(max_profile, i - min_price);
12         }
13         
14         return max_profile;
15     }
16 }
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-06
  • 2022-12-23
  • 2022-03-04
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-05
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2021-11-25
  • 2021-09-30
  • 2021-07-07
相关资源
相似解决方案