-
Notifications
You must be signed in to change notification settings - Fork 40
/
max_subarray_product_2_traversal.c
72 lines (62 loc) · 1.59 KB
/
max_subarray_product_2_traversal.c
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
/*
* Date: 2018-10-13
*
* Description:
* Given an unsorted array of integers, find max product of a subarray.
*
* Approach:
* Find max product of whole array while scanning in forward and backward
* direction. Max subarray product would be max of 2.
* Also, whenever 0 is encountered while scanning, reset max-so-far to 1.
*
* Complexity:
* O(N)
*/
#include "stdio.h"
#include "stdlib.h"
int main() {
int i = 0;
int n = 0;
int *a = NULL;
int max_fwd = 1, max_bkwd = 1, max_so_far = 1;
printf("Enter number of elements: ");
scanf("%d", &n);
a = (int *)malloc(sizeof(int)*n);
for (i = 0; i < n; i++) {
printf("Enter element[%d]: ", i);
scanf("%d", &a[i]);
}
// Max product while traversing in forward direction
for (i = 0; i < n; i++) {
max_so_far = max_so_far * a[i];
if (!max_so_far)
max_so_far = 1;
max_fwd = max_so_far > max_fwd ? max_so_far : max_fwd;
}
printf("max_fwd: %d\n", max_fwd);
// Max product while traversing in backward direction
max_so_far = 1;
for (i = n - 1; i >=0; i--) {
max_so_far = max_so_far * a[i];
if (!max_so_far)
max_so_far = 1;
max_bkwd = max_so_far > max_bkwd ? max_so_far : max_bkwd;
}
printf("max_bkwd: %d\n", max_bkwd);
printf("Maximum product of subarray is: %d\n",
max_fwd > max_bkwd ? max_fwd : max_bkwd);
return 0;
}
/*
* Output:
* -----------------------
* Enter number of elements: 5
* Enter element[0]: 5
* Enter element[1]: -2
* Enter element[2]: 3
* Enter element[3]: 4
* Enter element[4]: 5
* max_fwd: 5
* max_bkwd: 60
* Maximum product of subarray is: 60
*/