Created
November 20, 2014 06:17
-
-
Save rohith2506/1081c48070f4bf4e653e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Dynamic programming solution:- 0(n) | |
f(k) = max.product of numbers from 0 to k | |
g(k) = min.product of numbers from 0 to k | |
f(k) = max(f(k-1)*A[k], A[k], g(k-1)*A[k]); | |
g(k) = min(g(k-1)*A[k], A[k], f(k-1)*A[k]); | |
return f(n-1); | |
*/ | |
class Solution { | |
public: | |
int maxProduct(int A[], int n) { | |
int maxi = A[0]; | |
int mini = A[0]; | |
int total_max = A[0]; | |
for(int i=1; i<n; i++){ | |
int mx = maxi; | |
int mn = mini; | |
maxi = max(max(mx*A[i],A[i]),mn*A[i]); | |
mini = min(min(mx*A[i],A[i]),mn*A[i]); | |
total_max = max(total_max,maxi); | |
} | |
return total_max; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment