File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+
3
+ /**
4
+ * 循环版
5
+ * @param {number[] } prices
6
+ * @return {number }
7
+ */
8
+ let maxProfit = function ( prices ) {
9
+ let max = 0
10
+ for ( let i = 1 ; i < prices . length ; i ++ ) {
11
+ for ( let j = 0 ; j < i ; j ++ ) {
12
+ let price = prices [ j ]
13
+ let sale = prices [ i ] - price
14
+ max = Math . max ( max , sale )
15
+ }
16
+ }
17
+
18
+ return max
19
+ } ;
20
+
21
+
22
+ /**
23
+ * DP版
24
+ */
25
+ let maxProfit = function ( prices ) {
26
+ let n = prices . length
27
+ if ( ! n || n === 1 ) return 0
28
+
29
+ // 最大收益
30
+ let prevMax = 0
31
+ // 最小价格
32
+ let prevMin = prices [ 0 ]
33
+
34
+ for ( let i = 1 ; i < n ; i ++ ) {
35
+ let price = prices [ i ]
36
+
37
+ prevMax = Math . max ( price - prevMin , prevMax )
38
+ prevMin = Math . min ( price , prevMin )
39
+ }
40
+
41
+ return prevMax
42
+ } ;
43
+
44
+ console . log ( maxProfit ( [ 1 , 2 ] ) )
You can’t perform that action at this time.
0 commit comments