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 eeac423

Browse files
committedSep 4, 2024·
Feat: 152. Maximum Product Subarray
1 parent 1b32cdc commit eeac423

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed
 

‎maximum-product-subarray/HC-kang.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1+
/**
2+
* https://leetcode.com/problems/maximum-product-subarray
3+
* T.C. O(n)
4+
* S.C. O(1)
5+
* All numbers are integers, so multiplying two numbers cannot result in a smaller absolute value.
6+
* It's important to pay attention to zeros and negative numbers.
7+
*/
18
function maxProduct(nums: number[]): number {
2-
return 0;
9+
if (nums.length === 0) return 0;
10+
11+
let max = nums[0];
12+
let min = nums[0];
13+
let result = nums[0];
14+
15+
for (let i = 1; i < nums.length; i++) {
16+
const num = nums[i];
17+
if (num < 0) [max, min] = [min, max];
18+
19+
max = Math.max(num, max * num);
20+
min = Math.min(num, min * num);
21+
22+
result = Math.max(result, max);
23+
}
24+
25+
return result;
326
}

0 commit comments

Comments
 (0)
Please sign in to comment.