Skip to content

Instantly share code, notes, and snippets.

@htruong
Last active February 1, 2016 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htruong/11aabdac56da3be65a1e to your computer and use it in GitHub Desktop.
Save htruong/11aabdac56da3be65a1e to your computer and use it in GitHub Desktop.
// 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