File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } prices
3
+ * @return {number }
4
+ */
5
+
6
+ /**
7
+ * Runtime: 73ms, Memory: 59.38MB
8
+ * n = prices.length
9
+ * Time complexity: O(n)
10
+ * Space complexity: O(1)
11
+ *
12
+ */
13
+
14
+ var maxProfit = function ( prices ) {
15
+ let minPrice = prices [ 0 ] ;
16
+ let maxPrice = prices [ 0 ] ;
17
+ let answer = 0 ;
18
+
19
+ for ( let i = 1 ; i < prices . length ; i ++ ) {
20
+ answer = Math . max ( answer , maxPrice - minPrice ) ;
21
+
22
+ // 가장 뒤쪽 값이 max일 때
23
+ if ( maxPrice < prices [ i ] ) {
24
+ maxPrice = prices [ i ] ;
25
+ answer = Math . max ( answer , maxPrice - minPrice ) ;
26
+ continue ;
27
+ }
28
+ // 가장 뒷쪽 값이 min일 때
29
+ if ( minPrice > prices [ i ] ) {
30
+ minPrice = prices [ i ] ;
31
+ maxPrice = prices [ i ] ;
32
+ }
33
+ }
34
+ return answer ;
35
+ } ;
You can’t perform that action at this time.
0 commit comments