w3resource

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

Java Array: Exercise-65 with Solution

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.

Java Code Editor:

Previous: Write a Java program to find Longest Bitonic Subarray in a given array.
Next: Write a Java program to find contiguous subarray within a given array of integers which has the largest sum.

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.