-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
59 lines (51 loc) · 1.3 KB
/
res.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
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-04-13 10:10:59
*
* Find the contiguous subarray within an array (containing at least one number) which has the largest product.
* For example, given the array [2,3,-2,4],
* the contiguous subarray [2,3] has the largest product = 6.
*
* Solution idea: https://discuss.leetcode.com/topic/3607/sharing-my-solution-o-1-space-o-n-running-time
*
* @param {number[]} nums
* @return {number}
*/
let maxProduct = function(nums) {
let len = nums.length;
if (!len) {
return 0;
}
let maxPre = nums[0],
maxNow = nums[0],
minPre = nums[0];
for (let i = 1; i < len; i++) {
let maxVal = Math.max(maxPre * nums[i], minPre * nums[i], nums[i]),
minVal = Math.min(minPre * nums[i], maxPre * nums[i], nums[i]);
maxNow = Math.max(maxVal, maxNow);
maxPre = maxVal;
minPre = minVal;
}
return maxNow;
};
let maxProduct_2 = (nums) => {
let len = nums.length;
if (!len) {
return 0;
}
let maxNow = nums[0];
let imax = 1, imin = 1;
for (let i = 0; i < len; i++) {
if (nums[i] < 0) {
let tmp = imax;
imax = imin;
imin = tmp;
}
imax = Math.max(imax * nums[i], nums[i]),
imin = Math.min(imin * nums[i], nums[i]);
// console.log(imax, imin, nums[i])
maxNow = Math.max(maxNow, imax);
}
return maxNow;
}