# 122 Best Time to Buy and Sell Stock II

input一樣是一個array,裡面是某股票每天的價錢,可以無限制買進賣出,問最高總利潤是多少

  • idea: 一開始觀察了幾個case,發現只要一直更新min,一遇到比min大的就立刻賣,再把min設為Integer.MAX_VALUE,一般的case都可以對

    [7,1,4,3,6,5]
    
    min = 1
    price[i] = 4
    sum += 3
    
    min = 3
    price[i] = 5
    sum += 2
    
    最後 sum = 5
    ===================
    
    但如果有連續增加的數字會有錯誤
    [7,1,4,5,6,8]
    
    min = 1
    price[i] = 4
    sum += 3
    
    min = 5
    price[i] = 6
    sum += 1
    
    得到 sum = 4,但正確答案應該是 sum = 8-1 = 7
    

    觀察一下發現,(4-1) + (5-4) + (6-5) + (8-6) = 3+1+1+2 = 7,所以只要把重設min的方式改成min = price[i]就可以了。

  • pseudocode:

    //keep min, sum
    //for all price in prices
    //  if price[i] < min, update min, 
    //  else min = price[i]; sum += price[i] - min;
    
  • code:

    public class Solution {
      public int maxProfit(int[] prices) {
          int min = Integer.MAX_VALUE;
          int sum = 0;
    
          for(int i=0; i<prices.length; i++){
              if(prices[i] < min){
                  min = prices[i];
              }else{
                  sum += (prices[i] - min);
                  min = prices[i];
              }
          }
          return sum;
      }
    }
    

results matching ""

    No results matching ""