Created
July 3, 2014 10:09
-
-
Save aknow/0b7cc8b8b3fc5fbd3b1f to your computer and use it in GitHub Desktop.
This file contains 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
#include <iostream> | |
#include <vector> | |
#include <cassert> | |
using namespace std; | |
int findMaxProduct(vector<int> &nums) { | |
if (nums.empty()) return 0; | |
int best; | |
int maxProduct, minProduct; | |
best = maxProduct = minProduct = nums[0]; | |
for (unsigned i = 1; i < nums.size(); ++i) { | |
int n = nums[i]; | |
int n_max = n * maxProduct; | |
int n_min = n * minProduct; | |
maxProduct = max(n, max(n_max, n_min)); | |
minProduct = min(n, min(n_max, n_min)); | |
best = max(best, maxProduct); | |
} | |
return best; | |
} | |
vector<int> nums1 {2, -7, 0, 2, 3, 8, -6, 5}; | |
vector<int> nums2 {-2, 0, 3, 5, -7}; | |
vector<int> nums3 {2, -7, 0, 2, 3, 8, -6, 5, -1}; | |
vector<int> nums4 {-1, -2, -3}; | |
vector<int> nums5 {-1, 0, -3, 0, -2, 0}; | |
vector<int> nums6 {-1}; | |
vector<int> nums7 {-1, 1}; | |
vector<int> nums8 {-1, -1}; | |
int main() { | |
assert(findMaxProduct(nums1) == 48); | |
assert(findMaxProduct(nums2) == 15); | |
assert(findMaxProduct(nums3) == 1440); | |
assert(findMaxProduct(nums4) == 6); | |
assert(findMaxProduct(nums5) == 0); | |
assert(findMaxProduct(nums6) == -1); | |
assert(findMaxProduct(nums7) == 1); | |
assert(findMaxProduct(nums8) == 1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment