[ LeetCode ] 121 Best Time to Buy and Sell Stock

codesver·2023년 7월 5일
0

LeetCode

목록 보기
17/24
post-thumbnail

📌 Problem

0 이상 10,000 이하의 숫자가 담긴 100,000 이하 크기의 배열이 주어진다. Index가 오름차순인 순서대로 stock이 변한다고 하였을 때 최대의 이익을 남기려고 한다. 예를 들어 [7,1,5,3,6,4]이 주어졌을 때 1일 때 구매하여 6일 때 판매를 하여야 가장 큰 이익을 남길 수 있다. 만약 이익을 남길 수 없다면 0을 반환한다.

📌 Solution

Index를 순서대로 조회하면서 현재까지 조회한 stock과 현재 조회한 stock의 차이를 구한 후 현재 계산한 최대 이익보다 크면 업데이트를 한다.

📌 Code

class Solution {
    fun maxProfit(prices: IntArray) = prices.slice(1..prices.lastIndex)
        .fold(0 to prices.first()) { (maxProfit, minCost), cost ->
            max(maxProfit, cost - minCost) to min(minCost, cost)
        }.first
}
profile
Hello, Devs!

0개의 댓글