-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathMaximumPdt.java
56 lines (39 loc) · 1.32 KB
/
MaximumPdt.java
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
53
54
import java.io.*;
class Suhani {
// Function to find maximum product subarray
static int maxProduct(int arr[], int n)
{
// Variables to store maximum and minimum
// product till ith index.
int minVal = arr[0];
int maxVal = arr[0];
int maxProduct = arr[0];
for (int i = 1; i < n; i++)
{
// When multiplied by -ve number,
// maxVal becomes minVal
// and minVal becomes maxVal.
if (arr[i] < 0)
{
int temp = maxVal;
maxVal = minVal;
minVal =temp;
}
// maxVal and minVal stores the
// product of subarray ending at arr[i].
maxVal = Math.max(arr[i], maxVal * arr[i]);
minVal = Math.min(arr[i], minVal * arr[i]);
// Max Product of array.
maxProduct = Math.max(maxProduct, maxVal);
}
// Return maximum product found in array.
return maxProduct;
}
public static void main (String[] args)
{
int arr[] = { -1, -3, -10, 0, 60 };
int n = arr.length;
System.out.println( "Maximum Subarray product is "
+ maxProduct(arr, n));
}
}