Skip to content

Commit 868a665

Browse files
committed
up 26/02/22
1 parent f39c4d0 commit 868a665

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
## Maximum Product SubArray
2+
Given an array Arr[] that contains N integers (may be positive, negative or zero). Find the product of the maximum product subarray. [🔗Goto](https://practice.geeksforgeeks.org/problems/maximum-product-subarray3604/0/?page=1&difficulty[]=1&status[]=unsolved&company[]=Amazon&sortBy=submissions)
3+
4+
<details>
5+
<summary>Full Code</summary>
6+
7+
```java
8+
import java.io.*;
9+
import java.util.*;
10+
11+
public class Main {
12+
13+
public static void main(String[] args) throws Exception {
14+
BufferedReader br =
15+
new BufferedReader(new InputStreamReader(System.in));
16+
int tc = Integer.parseInt(br.readLine());
17+
while (tc-- > 0) {
18+
int n = Integer.parseInt(br.readLine());
19+
int[] arr = new int[n];
20+
String[] inputLine = br.readLine().split(" ");
21+
for (int i = 0; i < n; i++) {
22+
arr[i] = Integer.parseInt(inputLine[i]);
23+
}
24+
25+
System.out.println(new Solution().maxProduct(arr, n));
26+
}
27+
}
28+
}
29+
```
30+
</details>
31+
32+
```java
33+
class Solution {
34+
long maxProduct(int[] arr, int n) {
35+
long min = arr[0];
36+
long max = arr[0];
37+
long ans = arr[0];
38+
39+
for(int i=1; i<n; i++){
40+
if(arr[i]<0){
41+
long temp = min;
42+
min = max;
43+
max = temp;
44+
}
45+
max = Math.max(arr[i], max*arr[i]);
46+
min = Math.min(arr[i], min*arr[i]);
47+
48+
ans = Math.max(ans,max);
49+
}
50+
return ans;
51+
}
52+
}
53+
```

0 commit comments

Comments
 (0)