forked from its-harsshhh/DataStructures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum Product Subarray Problem.c
More file actions
56 lines (42 loc) · 1.35 KB
/
Maximum Product Subarray Problem.c
File metadata and controls
56 lines (42 loc) · 1.35 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
#include <stdio.h>
// Utility function to find a minimum of two numbers
int min(int x, int y) {
return (x < y) ? x : y;
}
// Utility function to find a maximum of two numbers
int max(int x, int y) {
return (x > y) ? x : y;
}
// Function to return the maximum product of a subarray of a given array
int findMaxProduct(int arr[], int n)
{
// base case
if (n == 0) {
return 0;
}
// maintain two variables to store the maximum and minimum product
// ending at the current index
int max_ending = arr[0], min_ending = arr[0];
// to store the maximum product subarray found so far
int max_so_far = arr[0];
// traverse the given array
for (int i = 1; i < n; i++)
{
int temp = max_ending;
// update the maximum product ending at the current index
max_ending = max(arr[i], max(arr[i] * max_ending, arr[i] * min_ending));
// update the minimum product ending at the current index
min_ending = min(arr[i], min(arr[i] * temp, arr[i] * min_ending));
max_so_far = max(max_so_far, max_ending);
}
// return maximum product
return max_so_far;
}
int main(void)
{
int arr[] = { -6, 4, -5, 8, -10, 0, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("The maximum product of a subarray is %d",
findMaxProduct(arr, n));
return 0;
}