628. Maximum Product of Three Numbers

 

Given an integer array nums, find three numbers whose product is maximum and return the maximum product.

 

Example 1:

Input: nums = [1,2,3]
Output: 6

Example 2:

Input: nums = [1,2,3,4]
Output: 24

Example 3:

Input: nums = [-1,-2,-3]
Output: -6 
 
class Solution {
public int maximumProduct(int[] nums) {
int maxA = Integer.MIN_VALUE, maxB = Integer.MIN_VALUE, maxC = Integer.MIN_VALUE;
int minA = Integer.MAX_VALUE, minB = Integer.MAX_VALUE;

for (int num : nums) {
// Update max values
if (num > maxA) {
maxC = maxB;
maxB = maxA;
maxA = num;
} else if (num > maxB) {
maxC = maxB;
maxB = num;
} else if (num > maxC) {
maxC = num;
}

// Update min values
if (num < minA) {
minB = minA;
minA = num;
} else if (num < minB) {
minB = num;
}
}

return Math.max(maxA * maxB * maxC, maxA * minA * minB);
}
}


 

Comments

Popular Posts