Contents

Creating maximum value 1 (with.Java)

   Mar 5, 2024     1 min read

This is an article about the “Creating the maximum value 1” problem.

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

  • 0 ≤ elements of numbers ≤ 10,000
  • 2 ≤ length of numbers ≤ 100

Input/Output Example

numbersresult
[1, 2, 3, 4, 5]20
[0, 31, 24, 10, 1, 9]744

My solution to the problem

import java.util.*;

class Solution {
     public int solution(int[] numbers) {
         int answer = 1;
         Arrays.sort(numbers);
         int endIdx = numbers.length - 1;
         for(int i = endIdx; i >= endIdx - 1; i--){
             answer *= numbers[i];
         }
         return answer;
     }
}

Solution explanation

  • Arrays.sort(numbers): Sorts an array.
  • endIdx: Calculates the last index of the array.
  • Use the for statement to select the two largest numbers and multiply them.

Code Advantages

  • Use sorting: Sorting allows you to quickly select the largest number.