File tree 2 files changed +31
-0
lines changed
2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change 128
128
120|[ Triangle] ( ./0120-triangle.js ) |Medium|
129
129
121|[ Best Time to Buy and Sell Stock] ( ./0121-best-time-to-buy-and-sell-stock.js ) |Easy|
130
130
122|[ Best Time to Buy and Sell Stock II] ( ./0122-best-time-to-buy-and-sell-stock-ii.js ) |Medium|
131
+ 123|[ Best Time to Buy and Sell Stock III] ( ./0123-best-time-to-buy-and-sell-stock-iii.js ) |Hard|
131
132
124|[ Binary Tree Maximum Path Sum] ( ./0124-binary-tree-maximum-path-sum.js ) |Hard|
132
133
125|[ Valid Palindrome] ( ./0125-valid-palindrome.js ) |Easy|
133
134
128|[ Longest Consecutive Sequence] ( ./0128-longest-consecutive-sequence.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 123. Best Time to Buy and Sell Stock III
3
+ * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
4
+ * Difficulty: Hard
5
+ *
6
+ * You are given an array prices where prices[i] is the price of a given stock on the ith day.
7
+ *
8
+ * Find the maximum profit you can achieve. You may complete at most two transactions.
9
+ *
10
+ * Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the
11
+ * stock before you buy again).
12
+ */
13
+
14
+ /**
15
+ * @param {number[] } prices
16
+ * @return {number }
17
+ */
18
+ var maxProfit = function ( prices ) {
19
+ const costs = [ prices [ 0 ] ] ;
20
+ const profits = new Array ( prices . length ) . fill ( 0 ) ;
21
+
22
+ for ( let i = 0 ; i < 2 ; i ++ ) {
23
+ for ( let j = 1 ; j < prices . length ; j ++ ) {
24
+ costs [ j ] = Math . min ( costs [ j - 1 ] , prices [ j ] - profits [ j ] ) ;
25
+ profits [ j ] = Math . max ( profits [ j - 1 ] , prices [ j ] - costs [ j ] ) ;
26
+ }
27
+ }
28
+
29
+ return profits [ profits . length - 1 ] ;
30
+ } ;
You can’t perform that action at this time.
0 commit comments