FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Algorithm-Solutions-Java/Arrays/MaxProduct.java at master · theprogrammedwords/Algorithm-Solutions-Java · GitHub
theprogrammedwords
/
Algorithm-Solutions-Java
Public
Notifications
You must be signed in to change notification settings
Fork
3
Star
6
Code
Issues
1
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Algorithm-Solutions-Java
/
Arrays
/
MaxProduct.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
56 lines (37 loc) · 1.24 KB
Breadcrumbs
Algorithm-Solutions-Java
/
Arrays
/
MaxProduct.java
Copy path
File metadata and controls
56 lines (37 loc) · 1.24 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
Problem Description
You are given an array consisting of n integers. Your task is to find the maximum product of 4 numbers in the array.
Input format
First line contains a single integer n - the number of elements in the array. Second line contains n space-separated integers - the array elements.
Output format
Print the maximum product of 4 numbers in the array.
Sample Input 1
6
-10 3 2 0 1 7
Sample Output 1
42
Explanation
We get the maximum product when we choose the elements {3,2,1,7}.
Constraints
4 <= n <= 10^5 -10^4 <= a[i] <= 10^4
*/
import
java
.
util
.*;
class
MaxProduct
{
public
static
void
main
(
String
args
[]) {
Scanner
sc
=
new
Scanner
(
System
.
in
);
int
n
=
sc
.
nextInt
();
int
arr
[] =
new
int
[
n
];
for
(
int
i
=
0
;
i
<
n
;
i
++)
arr
[
i
] =
sc
.
nextInt
();
long
res
=
maxProduct
(
n
,
arr
);
System
.
out
.
println
(
res
);
}
static
long
maxProduct
(
int
n
,
int
arr
[]) {
if
(
n
<
4
)
return
-
1
;
Arrays
.
sort
(
arr
);
long
x
= (
long
)
arr
[
n
-
4
] *
arr
[
n
-
3
] *
arr
[
n
-
2
] *
arr
[
n
-
1
];
long
y
= (
long
)
arr
[
0
] *
arr
[
1
] *
arr
[
2
] *
arr
[
3
];
long
z
= (
long
)
arr
[
0
] *
arr
[
1
] *
arr
[
n
-
1
] *
arr
[
n
-
2
];
return
(
long
)
Math
.
max
(
x
,
Math
.
max
(
y
,
z
));
}
}
Back
|
FazBrowse Home
|
New Git URL