-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximum Product Subarray (multiple ways).js
71 lines (59 loc) · 1.37 KB
/
Maximum Product Subarray (multiple ways).js
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
63
64
65
66
67
68
69
70
71
var maxProduct = function(nums)
{
let n, i = 0, len = nums.length, res = [[1], [1]];
for(; i < len; i++)
{
n = nums[i];
if(n < 0)
{
res[0][i+1] = Math.min((res[1][i] * n), n);
res[1][i+1] = Math.max((res[0][i] * n), n);
}
else
{
res[0][i+1] = Math.min((res[0][i] * n), n);
res[1][i+1] = Math.max((res[1][i] * n), n);
}
}
res[1][0] = -Infinity;
return Math.max(...res[1]);
};
///////////
var maxProduct = function(nums)
{
let n, i = 0, len = nums.length;
nums = [nums, [], []];
nums[1].length = len; nums[1].fill(1, 0, len);
nums[2].length = len; nums[2].fill(1, 0, len); nums[2][0] = -Infinity;
for(; i < len; i++)
{
n = nums[0][i];
if(nums < 0)
{
nums[1][i+1] = Math.min(nums[2][i] * n, n);
nums[2][i+1] = Math.max(nums[1][i] * n, n);
}
else
{
nums[1][i+1] = Math.min(nums[1][i] * n, n);
nums[2][i+1] = Math.max(nums[2][i] * n, n);
}
}
return Math.max(...nums[2]);
};
///////////
var maxProduct = function(nums)
{
let a, res = nums[0], len=nums.length, i = 0, ii;
for(; i < len; i++)
{
a = nums[i];
for(ii = i+1; ii < len; ii++)
{
res = res > a ? res : a;
a *= nums[ii];
}
res = res > a ? res : a;
}
return res;
};