Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fa86686

Browse files
committedJan 30, 2025
Add solution #123
1 parent 6ff4780 commit fa86686

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@
128128
120|[Triangle](./0120-triangle.js)|Medium|
129129
121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy|
130130
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|
131132
124|[Binary Tree Maximum Path Sum](./0124-binary-tree-maximum-path-sum.js)|Hard|
132133
125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy|
133134
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
};

0 commit comments

Comments
 (0)
Please sign in to comment.