-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathquestion34.c
More file actions
86 lines (67 loc) · 1.38 KB
/
question34.c
File metadata and controls
86 lines (67 loc) · 1.38 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
Find the max product sub array
METHOD:
Here we traverse the array from both the sides, handling corner cases.
Also the algorithm takes into account the number of negative numbers
Ignoring all the if cases, the problem can be solved just by traversing the array from both sides
This is not a DP question.
Another method listed at GFG
http://www.geeksforgeeks.org/maximum-product-subarray/
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void maxProductSubArray(int *arr, int size){
int i;
int countNegatives = 0;
for(i=0;i<size;i++){
if(arr[i] < 0){
countNegatives++;
}
}
int lastCountNegativesValues = countNegatives;
int curr = 1, max = INT_MIN;
for(i=0;i<size;i++){
curr = curr*arr[i];
if(curr > max){
max = curr;
}
if(arr[i] < 0){
countNegatives--;
}
if((curr < 0 && countNegatives <= 0) || (curr == 0)){
curr = 1;
}
}
curr = 1;
countNegatives = lastCountNegativesValues;
for(i=size-1;i>=0;i--){
curr = curr*arr[i];
if(curr > max){
max = curr;
}
if(arr[i] < 0){
countNegatives--;
}
if((curr < 0 && countNegatives <= 0) || (curr == 0)){
curr = 1;
}
}
printf("%d\n", max);
}
int main(){
int cases;
scanf("%d",&cases);
int i;
for(i=0;i<cases;i++){
int size;
scanf("%d",&size);
int j;
int arr[size];
for(j=0;j<size;j++){
scanf("%d",&arr[j]);
}
maxProductSubArray(arr, size);
}
return 0;
}