w3resource

Java: Find maximum difference between two elements in a given array of integers such that smaller element appears before larger element


65. Find maximum difference between two elements in an array

Write a Java program to find the maximum difference between two elements in a given array of integers such that the smaller element appears before the larger element.

Example:
Input :
nums = { 2, 3, 1, 7, 9, 5, 11, 3, 5 }
Output:
The maximum difference between two elements of the said array elements
10

Sample Solution:

Java Code:

// Import the necessary Java class.
import java.util.Arrays;

// Define a class named 'solution'.
class solution {
    // Method to find the maximum difference between two elements in the array.
    public static int diff_between_two_elemnts(int[] nums) {
        // Initialize a variable to store the maximum difference.
        int diff_two_elemnts = Integer.MIN_VALUE;

        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                // Update the maximum difference with the maximum of the current difference and the previous maximum.
                diff_two_elemnts = Integer.max(diff_two_elemnts, nums[j] - nums[i]);
            }
        }

        return diff_two_elemnts;
    }

    // Main method to demonstrate finding the maximum difference between two elements in an array.
    public static void main(String[] args) {
        // Initialize an array.
        int[] nums = { 2, 3, 1, 7, 9, 5, 11, 3, 5 };
        System.out.println("\nOriginal array: " + Arrays.toString(nums));

        // Call the 'diff_between_two_elemnts' method to find and print the maximum difference.
        System.out.print("The maximum difference between two elements of the said array elements\n" + diff_between_two_elemnts(nums));
    }
} 

Sample Output:

Original array: [2, 3, 1, 7, 9, 5, 11, 3, 5]
The maximum difference between two elements of the said array elements
10

Flowchart:

Flowchart: Find maximum difference between two elements in a given array of integers such that smaller element appears before larger element.

For more Practice: Solve these Related Problems:

  • Write a Java program to find the second largest difference between two elements in an array.
  • Write a Java program to find the maximum difference between any two elements in an unsorted array.
  • Write a Java program to find the smallest positive difference between two elements in an array.
  • Write a Java program to find two elements in an array that have the largest absolute difference.

Go to:


PREV : Find longest bitonic subarray in an array.
NEXT : Find subarray with largest sum in a given array.

Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.