Find the Maximum Product of Three numbers in a given array – Java (Leetcode 628)

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

Contents

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

Solution in Java :

class Solution {
    public int maximumProduct(int[] nums) {
         Arrays.sort(nums);
    int prod1 = nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3];
    int prod2 = nums[nums.length - 1] * nums[0] * nums[1];
    return prod1 > prod2 ? prod1 : prod2;
    }
}

Leave a Comment

Your email address will not be published.