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 546d3c2

Browse files
committedFeb 18, 2025
Add solution #309
1 parent c5dde59 commit 546d3c2

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@
236236
297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard|
237237
303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy|
238238
306|[Additive Number](./0306-additive-number.js)|Medium|
239+
309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
239240
316|[Remove Duplicate Letters](./0316-remove-duplicate-letters.js)|Medium|
240241
318|[Maximum Product of Word Lengths](./0318-maximum-product-of-word-lengths.js)|Medium|
241242
322|[Coin Change](./0322-coin-change.js)|Medium|
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 309. Best Time to Buy and Sell Stock with Cooldown
3+
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
4+
* Difficulty: Medium
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 as many transactions as you like
9+
* (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
10+
* - After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
11+
*
12+
* Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock
13+
* before you buy again).
14+
*/
15+
16+
/**
17+
* @param {number[]} prices
18+
* @return {number}
19+
*/
20+
var maxProfit = function(prices) {
21+
let result = 0;
22+
let remaining = 0;
23+
24+
for (let i = 0, limit = -Infinity; i < prices.length; i++) {
25+
limit = Math.max(limit, remaining - prices[i]);
26+
remaining = Math.max(remaining, result);
27+
result = limit + prices[i];
28+
}
29+
30+
return Math.max(result, remaining);
31+
};

0 commit comments

Comments
 (0)
Please sign in to comment.