FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/MaximumProductSubarray.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
MaximumProductSubarray.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
50 lines (41 loc) · 1.53 KB
Breadcrumbs
coding-Interview
/
MaximumProductSubarray.java
Copy path
File metadata and controls
50 lines (41 loc) · 1.53 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
com
.
leetcode
;
public
class
MaximumProductSubarray
{
//https://leetcode.com/problems/maximum-product-subarray/
/**
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
**/
class
Solution
{
/*
Many sub problem to simply took the pattern below.
// in once pass look for a max product of continious array from left to right
// in second pass look for a max product of continious array from right to left
// select max and return.
// Why it words ?
// it covers all continious array growing in either direction example input = [-2 1 3]-> [-2,-2,-6] and [3,3,-6] at each index we select max
*/
int
max
;
public
int
maxProduct
(
int
[]
nums
) {
max
=
Integer
.
MIN_VALUE
;
int
product
=
1
;
for
(
int
i
=
0
;
i
<
nums
.
length
;
i
++){
product
=
product
*
nums
[
i
];
max
=
Math
.
max
(
max
,
product
);
if
(
product
==
0
)
product
=
1
;
//reset for next continious array
}
product
=
1
;
//reset for right to left search
for
(
int
i
=
nums
.
length
-
1
;
i
>=
0
;
i
--){
product
=
product
*
nums
[
i
];
max
=
Math
.
max
(
max
,
product
);
if
(
product
==
0
)
product
=
1
;
//reset for next continious array
}
return
max
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL