Problem

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

Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,10^4] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

Solution

follow-up: max product of k numbers

class Solution {
    public int maximumProduct(int[] nums) {
        int len = nums.length;
        if (len < 3) return 0;
        Arrays.sort(nums);
        if (nums[0]*nums[len-1] >= 0) {
            return nums[len-1]*nums[len-2]*nums[len-3];
        }
        int l = 0, r = len-1, res = 1, count = 3;
        while (count > 0) {
            if (count%2 == 1) {
                res *= nums[r];
                r -= 1;
                count -= 1;
            }
            else {
                if (nums[r]*nums[r-1] > nums[l]*nums[l+1]) {
                    res *= nums[r]*nums[r-1];
                    r -= 2;
                } else {
                    res *= nums[l]*nums[l+1];
                    l += 2;
                }
                count -= 2;
            }
        }
        return res;
    }
}

linspiration
161 声望53 粉丝