-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathMaximum_Product_Subarray.java
More file actions
37 lines (32 loc) · 1010 Bytes
/
Maximum_Product_Subarray.java
File metadata and controls
37 lines (32 loc) · 1010 Bytes
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
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) {
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] inputLine = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(inputLine[i]);
}
System.out.println(new Solution().maxProduct(arr, n));
}
}
}
class Solution {
long maxProduct(int[] arr, int n) {
long maxSoFar = arr[0];
long minSoFar = arr[0];
long ans = maxSoFar;
for (int i = 1; i < n; i++) {
long curr = arr[i];
long tempMax = Math.max(curr, Math.max(maxSoFar * curr, minSoFar * curr));
minSoFar = Math.min(curr, Math.min(maxSoFar * curr, minSoFar * curr));
maxSoFar = tempMax;
ans = Math.max(ans, maxSoFar);
}
return ans;
}
}