Given an integer array nums
, find three numbers whose product is maximum and return the maximum product.
Example:
Input: arr[]={3,1,4,-5,-6,8} Output: 240 // -5*-6*8=240
Approach
Java
public class MaxProd3ElementArray {public static void main(String[] args) {// array must contains 3 elementsint arr[] = { 3, 1, 4, -5, -6, 8 };int n = arr.length;// i.e (-5)*(-6)*8int maximum = maximumProduct(arr, n);System.out.println(maximum);}// function to find the maximum product// of three numbers in the array// array must contains at least 3 elementsprivate static int maximumProduct(int[] arr, int n) {int max1 = Integer.MIN_VALUE;int max2 = Integer.MIN_VALUE;int max3 = Integer.MIN_VALUE;// find the maximum three elementsfor (int i = 0; i < n; i++) {// update max1,max2 and man3if (arr[i] > max1) {max3 = Math.max(max2, max3);max2 = Math.max(max2, max1);max1 = arr[i];}// update max2 and max3else if (arr[i] > max2) {max3 = Math.max(max2, max3);max2 = arr[i];}// update max3else if (arr[i] > max3)max3 = arr[i];}int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;// find the minimum two elementsfor (int i = 0; i < n; i++) {// update min1 and min2if (arr[i] < min1) {min2 = Math.min(min1, min2);min1 = arr[i];}// update min2else if (arr[i] < min2)min2 = arr[i];}// case 1: maximum=max1*max2*max3// case 2: maximum =min1*min2*max1return Math.max(min1 * min2 * max1, max1 * max2 * max3);}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the maximum product//of three numbers in the array//array must contains at least 3 elementsint maximumProduct(int arr[],int n){int max1=INT_MIN,max2=INT_MIN,max3=INT_MIN;//find the maximum three elementsfor(int i=0;i<n;i++){//update max1,max2 and man3if(arr[i]>max1){max3=max(max2,max3);max2=max(max2,max1);max1=arr[i];}//update max2 and max3else if(arr[i]>max2){max3=max(max2,max3);max2=arr[i];}//update max3else if(arr[i]>max3)max3=arr[i];}int min1=INT_MAX,min2=INT_MAX;//find the minimum two elementsfor(int i=0;i<n;i++){//update min1 and min2if(arr[i]<min1){min2=min(min1,min2);min1=arr[i];}//update min2else if(arr[i]<min2)min2=arr[i];}//case 1: maximum=max1*max2*max3//case 2: maximum =min1*min2*max1return max(min1*min2*max1,max1*max2*max3);}int main(){//array must contains 3 elementsint arr[]={3,1,4,-5,-6,8};int n=sizeof(arr)/sizeof(arr[0]);//i.e (-5)*(-6)*8int maximum=maximumProduct(arr,n);cout<<maximum<<"\n";return 0;}//Time Complexity: O(n)
No comments:
Post a Comment