Best Time to Buy and Sell Stock
Easy arrays · greedy
Description
Constraints
1 <= n <= 100000; 0 <= price
Examples
Input: prices = [7,1,5,3,6,4]
Output: 5
Buy at 1, sell at 6
Hints (1)
- Track the minimum price so far while scanning.
Solutions
Track running minimum and best profit. · Time O(n) · Space O(1)
func maxProfit(prices []int) int {
low := 1 << 62
best := 0
for _, p := range prices {
if p < low {
low = p
} else if p-low > best {
best = p - low
}
}
return best
}
Track running minimum and best profit. · Time O(n) · Space O(1)
function maxProfit(prices) {
let min = Infinity, best = 0;
for (const p of prices) {
if (p < min) min = p;
else if (p - min > best) best = p - min;
}
return best;
}
Track running minimum and best profit. · Time O(n) · Space O(1)
function maxProfit($prices) {
$min = PHP_INT_MAX;
$best = 0;
foreach ($prices as $p) {
if ($p < $min) {
$min = $p;
} elseif ($p - $min > $best) {
$best = $p - $min;
}
}
return $best;
}
Track running minimum and best profit. · Time O(n) · Space O(1)
def maxProfit(prices):
low = float("inf")
best = 0
for p in prices:
if p < low:
low = p
elif p - low > best:
best = p - low
return best
Track running minimum and best profit. · Time O(n) · Space O(1)
function maxProfit(prices: number[]): number {
let min = Infinity, best = 0;
for (const p of prices) {
if (p < min) min = p;
else if (p - min > best) best = p - min;
}
return best;
}
Create a free account to submit solutions, track progress and save problems.
Create account