Get startedGet started for free

Finding the max value in an array

In many data processing applications, memory efficiency is crucial. Your task is to implement a method that finds the maximum value in a large dataset.

This exercise is part of the course

Optimizing Code in Java

View Course

Exercise instructions

  • Initialize the max value in the findMaxValue method to the first element of the array.
  • Update max value when the current value is greater than it.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

public class Main {
    public static void main(String[] args) {
        DataAnalyzer analyzer = new DataAnalyzer();
        
        int[] smallData = {5, 3, 9, 1, 7};
        int maxSmall = analyzer.findMaxValue(smallData);
        System.out.println("Maximum value in small dataset: " + maxSmall);
        
        int[] largeData = new int[1000];
        for (int i = 0; i < largeData.length; i++) {
            largeData[i] = (int)(Math.random() * 10000);
        }
        
        int maxLarge = analyzer.findMaxValue(largeData);
        System.out.println("Maximum value in large dataset: " + maxLarge);
    }
}

class DataAnalyzer {
    public int findMaxValue(int[] data) {
        // Initialize the maximum value to the first element
        int max = ____;
        
        for (int value : data) {
            // Update max if current element is greater
            if (____) {
                max = value;
            }
        }
        
        return max;
    }
}
Edit and Run Code