63. 股票的最大利润

题目链接

Leetcode:121. Best Time to Buy and Sell Stock

题目描述

可以有一次买入和一次卖出,买入必须在前。求最大收益。

63. 股票的最大利润 - 图1

解题思路

使用贪心策略,假设第 i 轮进行卖出操作,买入操作价格应该在 i 之前并且价格最低。

  1. public int maxProfit(int[] prices) {
  2. if (prices == null || prices.length == 0)
  3. return 0;
  4. int soFarMin = prices[0];
  5. int maxProfit = 0;
  6. for (int i = 1; i < prices.length; i++) {
  7. soFarMin = Math.min(soFarMin, prices[i]);
  8. maxProfit = Math.max(maxProfit, prices[i] - soFarMin);
  9. }
  10. return maxProfit;
  11. }

63. 股票的最大利润 - 图2