Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 725e20c

Browse files
Create MaxProduct.java
1 parent acee3d2 commit 725e20c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎MaxProduct.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Problem Description
3+
You are given an array consisting of n integers. Your task is to find the maximum product of 4 numbers in the array.
4+
5+
Input format
6+
First line contains a single integer n - the number of elements in the array. Second line contains n space-separated integers - the array elements.
7+
8+
Output format
9+
Print the maximum product of 4 numbers in the array.
10+
11+
Sample Input 1
12+
6
13+
-10 3 2 0 1 7
14+
15+
Sample Output 1
16+
42
17+
18+
Explanation
19+
We get the maximum product when we choose the elements {3,2,1,7}.
20+
21+
Constraints
22+
4 <= n <= 10^5 -10^4 <= a[i] <= 10^4
23+
*/
24+
import java.util.*;
25+
26+
class MaxProduct {
27+
public static void main(String args[]) {
28+
Scanner sc = new Scanner(System.in);
29+
30+
int n = sc.nextInt();
31+
32+
int arr[] = new int[n];
33+
for (int i = 0; i < n; i++)
34+
arr[i] = sc.nextInt();
35+
36+
long res = maxProduct(n, arr);
37+
38+
System.out.println(res);
39+
40+
}
41+
42+
static long maxProduct(int n, int arr[]) {
43+
44+
if(n< 4) return -1;
45+
46+
Arrays.sort(arr);
47+
48+
long x = (long) arr[n-4] * arr[n-3] * arr[n-2] * arr[n-1];
49+
long y = (long) arr[0] * arr[1] * arr[2] * arr[3];
50+
long z = (long) arr[0] * arr[1] * arr[n-1] * arr[n-2];
51+
52+
53+
return (long) Math.max(x, Math.max(y, z));
54+
}
55+
56+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /