File tree 1 file changed +29
-0
lines changed
best-time-to-buy-and-sell-stock
1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments