Skip to content

Commit cb92945

Browse files
committed
feat: add Maximum Product Subarray
1 parent dd94ff4 commit cb92945

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ Roadmap: https://neetcode.io/roadmap
8787
| 647 | [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/description/) | Medium | [ts](./TypeScript/647.palindromic-substrings.ts) | 1-D DP |
8888
| 91 | [Decode Ways](https://leetcode.com/problems/decode-ways/description/) | Medium | [ts](./TypeScript/91.decode-ways.ts) | 1-D DP |
8989
| 300 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/description/) | Medium | [ts](./TypeScript/300.longest-increasing-subsequence.ts) | 1-D DP |
90+
| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/description/) | Medium | [ts](./TypeScript/152.maximum-product-subarray.ts) | 1-D DP |
9091

9192
### Others
9293

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function maxProduct(nums: number[]): number {
2+
let result = nums[0];
3+
let currentMax = nums[0];
4+
let currentMin = nums[0];
5+
6+
for (let i = 1; i < nums.length; i++) {
7+
const temp = currentMax;
8+
9+
currentMax = Math.max(temp * nums[i], currentMin * nums[i], nums[i]);
10+
currentMin = Math.min(temp * nums[i], currentMin * nums[i], nums[i]);
11+
12+
if (currentMax > result) {
13+
result = currentMax;
14+
}
15+
}
16+
17+
return result;
18+
}
19+
20+
console.log(maxProduct([2, 3, -2, 4]));
21+
console.log(maxProduct([-2, 0, -1]));

0 commit comments

Comments
 (0)