Contents

Find largest number (with.Java)

   Feb 29, 2024     2 min read

This article examines the problem of “Finding the largest number.”

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

When an integer array array is given as a parameter, complete the solution function to return an array containing the largest number and its index.

Restrictions

  • 1 ≤ length of array ≤ 100
  • 0 ≤ array element ≤ 1,000
  • There are no duplicate numbers in the array.

Input/Output Example

arrayresult
[1, 8, 3][8, 1]
[9, 10, 11, 8][11, 2]

My solution to the problem

class Solution {
     public int[] solution(int[] array) {
         int[] answer = new int[2];
         int temp = 0;
         int idx = 0;
         for(int i = 0; i < array.length; i++){
             if(temp < array[i]){
                 temp = array[i];
                 idx = i;
             }
         }

         answer[0] = temp;
         answer[1] = idx;
         return answer;
     }
}

Solution explanation

  • First, an int array answer of size 2 is declared and initialized. This array is used to store the results.
  • Additionally, int variables temp and idx are also declared and initialized to 0.
  • temp is a variable that stores the maximum value to date, and idx is a variable that stores the index of the maximum value.
  • Next, iterate over the array using a for statement.
  • Access each element of the array and compare it to temp. If the current element is greater than temp, update temp and idx.
  • In other words, when a value larger than the current maximum value is encountered, temp and idx are updated and the corresponding value and index are recorded.
  • When the for statement ends, temp and idx will have the largest value and the index of that value.
  • Store this value in the answer array and return the answer array.