forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwogha95.js
More file actions
39 lines (36 loc) Β· 1.1 KB
/
wogha95.js
File metadata and controls
39 lines (36 loc) Β· 1.1 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
// TC: O(N)
// SC: O(1)
/**
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function (nums) {
let maximumProduct = Number.MIN_SAFE_INTEGER;
let subProduct = 1;
// 1. μ’μμ μ°λ‘ λμ κ³±μ μ μ₯νκΈ° μν΄ μν
for (let index = 0; index < nums.length; index++) {
// 2. 0μ λ§λλ©΄ λμ κ³±μ κ³±νμ§ μκ³ 1λ‘ μ΄κΈ°ν
if (nums[index] === 0) {
maximumProduct = Math.max(maximumProduct, 0);
subProduct = 1;
continue;
}
// 3. λ§€λ² λμ κ³±μ κ°±μ
subProduct *= nums[index];
maximumProduct = Math.max(maximumProduct, subProduct);
}
subProduct = 1;
// 4. μ°μμ μ’λ‘ λμ κ³±μ μ μ₯νκΈ° μν΄ μν
for (let index = nums.length - 1; index >= 0; index--) {
// 5. 0μ λ§λλ©΄ λμ κ³±μ κ³±νμ§ μκ³ 1λ‘ μ΄κΈ°ν
if (nums[index] === 0) {
maximumProduct = Math.max(maximumProduct, 0);
subProduct = 1;
continue;
}
// 6. λ§€λ² λμ κ³±μ κ°±μ
subProduct *= nums[index];
maximumProduct = Math.max(maximumProduct, subProduct);
}
return maximumProduct;
};