1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+ < head >
4
+ < meta charset ="UTF-8 ">
5
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6
+ < meta http-equiv ="X-UA-Compatible " content ="ie=edge ">
7
+ < title > Document</ title >
8
+ </ head >
9
+ < body >
10
+ < script >
11
+ // Source : https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
12
+ // Author : 悬笔e绝
13
+ // Date : 2019-06-05
14
+
15
+ /**
16
+ * @param {number[] } prices
17
+ * @return {number }
18
+ */
19
+ var maxProfit = function ( prices ) {
20
+ var len = prices . length
21
+ , sell = [ ]
22
+ , buy = [ ]
23
+ , item
24
+ , i ;
25
+
26
+ if ( ! len )
27
+ return 0 ;
28
+
29
+ for ( i = 0 ; i < len ; i ++ ) {
30
+ sell [ i ] = [ ] ,
31
+ buy [ i ] = [ ] ,
32
+ item = prices [ i ] ;
33
+ if ( ! i ) {
34
+ sell [ i ] [ 0 ] = 0 ;
35
+ sell [ i ] [ 1 ] = 0 ;
36
+ sell [ i ] [ 2 ] = 0 ;
37
+ buy [ i ] [ 0 ] = - item ;
38
+ buy [ i ] [ 1 ] = - item ;
39
+ buy [ i ] [ 2 ] = - item ;
40
+ } else {
41
+ sell [ i ] [ 0 ] = sell [ i - 1 ] [ 0 ] ;
42
+ sell [ i ] [ 1 ] = Math . max ( sell [ i - 1 ] [ 1 ] , buy [ i - 1 ] [ 1 ] + item ) ;
43
+ sell [ i ] [ 2 ] = Math . max ( sell [ i - 1 ] [ 2 ] , buy [ i - 1 ] [ 2 ] + item ) ;
44
+ buy [ i ] [ 0 ] = buy [ i - 1 ] [ 0 ] ;
45
+ buy [ i ] [ 1 ] = Math . max ( buy [ i - 1 ] [ 1 ] , sell [ i - 1 ] [ 0 ] - item ) ;
46
+ buy [ i ] [ 2 ] = Math . max ( buy [ i - 1 ] [ 2 ] , sell [ i - 1 ] [ 1 ] - item ) ;
47
+ }
48
+ }
49
+ return sell [ len - 1 ] [ 2 ] ;
50
+ } ;
51
+
52
+ // 测试
53
+ var prices1 = [ 3 , 3 , 5 , 0 , 0 , 3 , 1 , 4 ] ;
54
+ console . log ( maxProfit ( prices1 ) ) ;
55
+ var prices2 = [ 1 , 2 , 3 , 4 , 5 ] ;
56
+ console . log ( maxProfit ( prices2 ) ) ;
57
+ var prices3 = [ 7 , 6 , 4 , 3 , 1 ] ;
58
+ console . log ( maxProfit ( prices3 ) ) ;
59
+
60
+ </ script >
61
+ </ body >
62
+ </ html >
0 commit comments