Arrays: Best Time to Buy and Sell Stock — Kotlin Solution
Arrays: Best Time to Buy and Sell Stock — Kotlin Solution
Problem Info
| LeetCode # | 121 — Best Time to Buy and Sell Stock |
| Difficulty | Easy |
| Topic | Arrays, Greedy, Sliding Window |
Given an array
priceswhereprices[i]is the price on dayi, return the maximum profit from a single buy-sell transaction.
Example:
1
2
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5 // Buy at 1, sell at 6
Approach
We can’t sell before we buy — so we track the minimum price seen so far and at each step compute potential profit.
No nested loops needed. Single pass.
Kotlin Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fun maxProfit(prices: IntArray): Int {
var minPrice = Int.MAX_VALUE
var maxProfit = 0
for (price in prices) {
if (price < minPrice) {
minPrice = price
} else {
maxProfit = maxOf(maxProfit, price - minPrice)
}
}
return maxProfit
}
Why Kotlin Shines Here
maxOf() — cleaner than Math.max():
1
2
maxProfit = maxOf(maxProfit, price - minPrice)
// vs Java: maxProfit = Math.max(maxProfit, price - minPrice);
for (price in prices) — no index needed when you don’t need it:
1
2
for (price in prices)
// vs Java: for (int price : prices)
Complexity
| Time | O(n) — single pass through prices |
| Space | O(1) — only two variables |
Key Takeaway
Track the minimum price seen so far. At each step, profit = current price − minimum so far. Keep the max of all profits.
📚 Kotlin DSA Series
This post is part of the Kotlin DSA series — solving LeetCode problems using idiomatic Kotlin.
← View Full Series Index
This post is part of the Kotlin DSA series — solving LeetCode problems using idiomatic Kotlin.
← View Full Series Index
This post is licensed under CC BY 4.0 by the author.