Leetcode 122) Best Time to Buy and Sell Stock

image

  • 작은 값 -> 큰 값 으로 갈 때를 잡아서 계산해줬다.
class Solution {
    public int maxProfit(int[] prices) {
        //low를 뭘로 하지?
        int minInd=0;
        int maxInd=0;
        int sum = 0;
        for(int i =0;i<prices.length-1;i++){
            int j=i+1;
            //뒤에 코드에서 i--해주면, 이게 바로 만족된다. 그래서 속도가 빨라진다..
            while(prices[i] >= prices[j]){
                i++;
                j++;
                if(j==prices.length){
                    return sum;
                }
            }
            minInd = i;
            while(prices[i] <= prices[j]){
                i++;
                j++;
                if(j==prices.length){
                    break;
                }
            } 
            maxInd = i;
            sum+=prices[maxInd]-prices[minInd];  
            //이 i--없어도 작동한다. 근데 i--있는게 훨씬 빠르다. 왜지?
            //아! 아마 prices[i] <= prices[j] 위에 이 조건을 바로 만족시킬 수 있어서 그런가보다.
            i--;
        }
        return sum;
    }
}

다른 풀이

class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0) {
            return 0;
        }
        int profit = 0;
        //더해서 하는것도 똑같이 나오기 때문에.이렇게 해도 된다.
        for(int i = 0; i < prices.length - 1; i++) {
            if(prices[i] < prices[i+1]) {
                profit += prices[i+1] - prices[i];
            }
        }
        return profit;
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2