Created
March 31, 2022 18:24
-
-
Save ricky-lim/508d02a8a4224b491743a8d862e584aa to your computer and use it in GitHub Desktop.
Find max products
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
class Scratch { | |
public static int maxProduct(int[] numbers) { | |
int length = numbers.length; | |
if (length < 2) { | |
throw new IllegalArgumentException(String.format("Require at least 2 numbers. But given: %s", Arrays.toString(numbers))); | |
} | |
int min1 = numbers[0]; | |
int min2 = Integer.MAX_VALUE; | |
int max1 = numbers[0]; | |
int max2 = Integer.MIN_VALUE; | |
for (int i = 1; i < numbers.length; i++) { | |
if (numbers[i] < min1) { | |
min2 = min1; | |
min1 = numbers[i]; | |
} else if (numbers[i] < min2) { | |
min2 = numbers[i]; | |
} else if (numbers[i] > max1) { | |
max2 = numbers[i]; | |
} else if (numbers[i] > max2) { | |
max2 = numbers[i]; | |
} | |
} | |
return Math.max((min1 * min2), (max1 * max2)); | |
} | |
public static void main(String[] args) { | |
int[] nums1 = {3, 2, 1, 4, 1}; | |
int[] nums2 = {3, 1, 4, 5, 2}; | |
int[] nums3 = {-1, -5, -4, 2, 5}; | |
System.out.println(maxProduct(nums1)); | |
System.out.println(maxProduct(nums2)); | |
System.out.println(maxProduct(nums3)); | |
// Should be error | |
int[] errorNum1 = {2}; | |
System.out.println(maxProduct(errorNum1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment