알고리즘/Array

Best Time to Buy and Sell Stock

e-pd 2020. 11. 20. 20:17

leetcode.com/problems/best-time-to-buy-and-sell-stock/

 

Best Time to Buy and Sell Stock - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;
 
class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0, minProfit = Integer.MAX_VALUE;
        
        for (int price : prices) {
            minProfit = Math.min(minProfit, price);
            maxProfit = Math.max(maxProfit, price - minProfit);
        }
        return maxProfit;
    }
}
cs

 

가장 이득을 보기위해서 가격을 순회하면서 가장 작은 값과 차이를 구해야한다.

최소값을 현재 배열의 순회값과 기존 최솟값과 비교해 갱신한다.

최댓값은 현재 배열의 순회값에서 최소값과 최댓값 비교한것을 갱신한다.