-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxproduct.cpp
More file actions
49 lines (45 loc) · 1.07 KB
/
maxproduct.cpp
File metadata and controls
49 lines (45 loc) · 1.07 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
#include <iostream>
#include <assert.h>
#include <stack>
using namespace std;
/*
public class Solution {
public int maxProduct(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int[] f = new int[A.length];
int[] g = new int[A.length];
f[0] = A[0];
g[0] = A[0];
int res = A[0];
for (int i = 1; i < A.length; i++) {
f[i] = Math.max(Math.max(f[i - 1] * A[i], g[i - 1] * A[i]), A[i]);
g[i] = Math.min(Math.min(f[i - 1] * A[i], g[i - 1] * A[i]), A[i]);
res = Math.max(res, f[i]);
}
return res;
}
}
*/
int maxproduct(int *arr, int n)
{
int maxproduct = arr[0];
int max = arr[0];
int min = arr[0];
for (int i = 1; i< n; ++i)
{
int temp = max;
max = std::max( std::max( arr[i] * max, arr[i] ), arr[i] * min );
min = std::min( std::min( arr[i] * temp, arr[i] ), arr[i] * min );
maxproduct = std::max(max, maxproduct);
}
return maxproduct;
}
// Driver program to test abive function
int main()
{
int a[] = {-2, -3, 0, -2, -40};
cout<<maxproduct(a, sizeof(a)/sizeof(a[0]))<<endl;
return 0;
}