Creating maximum value 2 (with.Java)
This article looks into the problem of “Creating the maximum value 2 (with.Java)”.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
The integer array numbers is given as a parameter.
Complete the solution function to return the maximum value that can be created by multiplying two of the elements of numbers.
Restrictions
- -10,000 ≤ elements of numbers ≤ 10,000
- 2 ≤ length of numbers ≤ 100
Input/Output Example
numbers | result |
---|---|
[1, 2, -3, 4, -5] | 15 |
[0, -31, 24, 10, 1, 9] | 240 |
[10, 20, 30, 5, 5, 20, 5] | 600 |
My solution to the problem
import java.util.Arrays;
class Solution {
public int solution(int[] numbers) {
Arrays.sort(numbers);
int n = numbers.length;
int maxNegative = numbers[0] * numbers[1];
int maxPositive = numbers[n - 1] * numbers[n - 2];
return Math.max(maxNegative, maxPositive);
}
}
Solution explanation
- Array sorting: Sorts the given array to distinguish between negative and positive numbers.
- Select the two largest negative numbers: Select the first and second elements of the sorted array and calculate the product of the two largest negative numbers.
- Select the two largest positive numbers: Select the last and second-to-last elements of the sorted array and calculate the product of the two largest positive numbers.
- Return result: Returns the larger value of the product of a negative number and a positive number.
Code Advantages
- Simple logic: I used a simple method of sorting an array, picking the largest number and the second largest number and multiplying them.
- Efficiency through sorting: We implemented the process of selecting the largest number quickly and simply using a sorted array.
Code Disadvantages
- Time complexity due to array sorting: The time complexity for the process of sorting an array is O(n log n), which may affect performance if the array is large.