Best Time to Buy and Sell Stock - LeetCode
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4
주어진 가격 리스트를 순회하며, 최솟값을 갱신하고 (가격 - 최솟값)의 최댓값을 찾으면 된다.
사실상 구현
배열 순회
가격의 최솟값 갱신
(현재 가격 - 최솟값)의 최댓값 갱신
class Solution {
fun maxProfit(prices: IntArray): Int {
var answer = 0
var low = prices[0]
for (idx in 1 until prices.size) {
low = minOf(low, prices[idx]) // 최솟값 갱신 (구입 가격)
if (prices[idx] <= answer) continue
answer = maxOf(answer, prices[idx] - low) // 최대 수익 갱신
}
return answer
}
}
시간 복잡도: 배열 순회 = n