-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum product subarray
52 lines (40 loc) · 1.2 KB
/
Maximum product subarray
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
//Maximum product subarray
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine());
while(tc-- > 0) {
String[] inputLine = br.readLine().split(" ");
int n = inputLine.length;
int[] arr = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(inputLine[i]);
}
System.out.println(new Solution().maxProduct(arr));
}
}
}
class Solution {
int maxProduct(int[] arr) {
int max = Integer.MIN_VALUE;
int pro = 1;
for(int i = 0; i < arr.length; i++) {
pro *= arr[i];
max = Math.max(max, pro);
if(pro == 0) {
pro = 1;
}
}
pro = 1;
for(int i = arr.length - 1; i >= 0; i-- ) {
pro *= arr[i];
max = Math.max(max, pro);
if(pro == 0) {
pro = 1;
}
}
return max;
}
}