forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_628.java
48 lines (42 loc) · 1.34 KB
/
_628.java
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
package com.fishercoder.solutions;
import java.util.Arrays;
/**
* 628. Maximum Product of Three Numbers
*
* 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,104] 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.
*/
public class _628 {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int product = 1;
if (nums.length >= 3) {
for (int i = nums.length - 1; i >= nums.length - 3; i--) {
product *= nums[i];
}
int anotherProduct = nums[0] * nums
[1] * nums[nums.length - 1];
product = Math.max(product, anotherProduct);
} else {
for (int i = 0; i < nums.length; i++) {
product *= nums[i];
}
}
return product;
}
public static void main(String... args) {
_628 test = new _628();
// int[] nums = new int[]{1,2,3};
// int[] nums = new int[]{1,2,3,4};
int[] nums = new int[]{-4, -3, -2, -1, 60};
System.out.println(test.maximumProduct(nums));
}
}