We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1b32cdc commit eeac423Copy full SHA for eeac423
maximum-product-subarray/HC-kang.ts
@@ -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
+ */
8
function maxProduct(nums: number[]): number {
- 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;
26
}
0 commit comments