본문 바로가기
문제풀이

Leetcode Best Time to Buy and Sell Stock JAVA

by AndoneKwon 2021. 1. 4.

이 문제는 언듯 보기에 N^2으로 풀어야 할거 같지만..

아니다..

왜냐면 그 상황에서 가장 작은 배열의 요소를 빼주면 되기 떄문이다.(뒷 부분에 더 작은 것이 있다면 그것을 이용한다)
그래서 그 구한 값이 최대가 되는 값을 모든 배열 요소에 대해서 업데이트 해주면 된다.

class Solution {
    public int maxProfit(int[] prices) {
        int priceMin = Integer.MAX_VALUE;
        int answerMax = 0;
        for(int item : prices){
            priceMin = Math.min(priceMin,item);
            answerMax = Math.max(answerMax,item-priceMin);
        }
        return answerMax;
    }
}

'문제풀이' 카테고리의 다른 글

Leetcode Climbing Stairs JAVA  (0) 2021.01.04
Leetcode Happy Number JAVA  (0) 2021.01.04
Leetcode Number of 1 Bits JAVA  (0) 2021.01.04
Leetcode Intersection of Two Arrays II JAVA  (0) 2020.12.28
LeetCode Missing Number JAVA  (0) 2020.12.26