-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0152-maximum-product-subarray.js
More file actions
62 lines (50 loc) · 1.45 KB
/
0152-maximum-product-subarray.js
File metadata and controls
62 lines (50 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Brute Force - Linear Search
* Time O(N^2) | Space O(1)
* https://leetcode.com/problems/maximum-product-subarray/
* @param {number[]} nums
* @return {number}
*/
var maxProduct = (nums) => {
const isEmpty = nums.length === 0;
if (isEmpty) return 0;
return linearSearch(nums); /* Time O(N * N) */
};
const linearSearch = (nums, max = nums[0]) => {
for (let index = 0; index < nums.length; index++) {
/* Time O(N) */
max = getMax(nums, index, max); /* Time O(N) */
}
return max;
};
const getMax = (nums, index, max, product = 1) => {
for (let num = index; num < nums.length; num++) {
/* Time O(N) */
product *= nums[num];
max = Math.max(max, product);
}
return max;
};
/**
* Greedy - product
* Time O(N) | Space O(1)
* https://leetcode.com/problems/maximum-product-subarray/
* @param {number[]} nums
* @return {number}
*/
var maxProduct = (nums) => {
const isEmpty = nums.length === 0;
if (isEmpty) return 0;
return greedySearch(nums); /* Time O(N) */
};
const greedySearch = (nums) => {
let min = (max = product = nums[0]);
for (let num = 1; num < nums.length; num++) {
/* Time O(N) */
const [minProduct, maxProduct] = [min * nums[num], max * nums[num]];
min = Math.min(maxProduct, minProduct, nums[num]);
max = Math.max(maxProduct, minProduct, nums[num]);
product = Math.max(product, max);
}
return product;
};