Last active
February 1, 2016 20:09
-
-
Save htruong/11aabdac56da3be65a1e 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
// MaxProduct solution | |
// Huan Truong | |
// For those who are too lazy to think, like me | |
int maxProduct(int* nums, int numsSize) { | |
int bestSoFar = nums[0]; | |
// Max magnitute product we have in a single "segment" | |
int maxp = nums[0]; | |
// Smallest magnitute product we have | |
int minp = nums[0]; | |
for (unsigned int i = 1; i < numsSize; ++i) { | |
int num = nums[i]; | |
// Worst we can do is to reset and start from the number we are looking at. | |
if (maxp <= 0) maxp = 1; | |
if (num >= 0) { | |
// We just multiply what we had in | |
maxp = maxp * num; | |
minp = minp * num; | |
} else { // num < 0 | |
// Swap the max magnitute and the min magnitute, because the negative flips everything | |
int prevmaxp = maxp; | |
maxp = minp * num; | |
minp = prevmaxp * num; | |
} | |
if (maxp > bestSoFar) bestSoFar = maxp; | |
} | |
return bestSoFar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment