Skip to content

Commit 98eaeb2

Browse files
committed
best-time-to-buy-and-sell-stock
1 parent d2bc9df commit 98eaeb2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* 121. Best Time to Buy and Sell Stock
3+
* You are given an array prices where prices[i] is the price of a given stock on the ith day.
4+
* You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
5+
* Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
6+
*
7+
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
8+
*/
9+
10+
// O(n) time
11+
// O(n) space
12+
function maxProfit(prices: number[]): number {
13+
let highestProfit = 0;
14+
let left = 0;
15+
let right = 1;
16+
17+
while (right < prices.length) {
18+
if (prices[left] < prices[right]) {
19+
let profit = prices[right] - prices[left];
20+
highestProfit = Math.max(highestProfit, profit);
21+
} else {
22+
left = right;
23+
}
24+
25+
right++;
26+
}
27+
28+
return highestProfit;
29+
}

0 commit comments

Comments
 (0)