[leetcode]股票最大利润

1,041 阅读1分钟

题目:股票最大利润

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

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

题解一:暴力破解两层循环

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

题解二:一次遍历

      class Solution {
          public int maxProfit(int[] prices) {
              int profit = 0;
              if(prices.length == 0){
                  return profit;
              }
              int min = prices[0];
              for(int i = 0;i<prices.length;i++){
                  min = Math.min(min,prices[i]);
                  profit = Math.max(prices[i]-min,profit);
              }
              return profit;
      
          }
      }

更多精彩内容请关注公众号