Skip to content
Advertisement

Find 2D array max and min

This is the original prompt:

Find the maximum value and minimum value in milesTracker. Assign the maximum value to maxMiles, and the minimum value to minMiles. Sample output for the given program:

Min miles: -10 
Max miles: 40

Here is my code:

import java.util.Scanner;

public class ArraysKeyValue {
  public static void main (String [] args) {   
    final int NUM_ROWS = 2;
    final int NUM_COLS = 2;
    int [][] milesTracker = new int[NUM_ROWS][NUM_COLS];
    int i = 0;
    int j = 0;
    int maxMiles = 0; 
    int minMiles = 0; 

    milesTracker[0][0] = -10;
    milesTracker[0][1] = 20;
    milesTracker[1][0] = 30;
    milesTracker[1][1] = 40;

    for(i=0;i<NUM_ROWS;++i) {
     
       for(j=0;j<NUM_COLS;++j) {
         
          if (milesTracker[i][j]<minMiles){
              minMiles = milesTracker[i][j]; 
          }
          else if (milesTracker[i][j] > maxMiles){
              maxMiles = milesTracker[i][j];
          }
       } 
    }

    System.out.println("Min miles: " + minMiles);
    System.out.println("Max miles: " + maxMiles);
  }
}

Here is the output:

  Testing with milesTracker = {{-10, 20}, {30, 40}}

Your output:

Min miles: -10
Max miles: 40

   Testing with milesTracker = {{73, 0}}

Your output:

Min miles: 0
Max miles: 73

✖   Testing with milesTracker = {{-5}, {-93}, {-259}}

Expected output:

Min miles: -259
Max miles: -5

Your output:

Min miles: -259
Max miles: 0

Why is the last test failing?

Advertisement

Answer

As an addition to @Fikolev’s answer: If you are only allowed to edit the loop bodies, you can move the initialization there:

for(i=0;i<NUM_ROWS;++i) {
  for(j=0;j<NUM_COLS;++j) {
    if (i == 0 && j == 0) {
      maxMiles = Integer.MIN_VALUE; 
      minMiles = Integer.MAX_VALUE; 
    }
  ...
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement