Java Array Exercises: 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 maximum difference between two elements in a given array of integers such that smaller element appears before 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 java.util.Arrays;
class solution
{
public static int diff_between_two_elemnts(int[] nums)
{
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++) {
diff_two_elemnts = Integer.max(diff_two_elemnts,nums[j] - nums[i]);
}
}
return diff_two_elemnts;
}
public static void main(String[] args)
{
int[] nums = { 2, 3, 1, 7, 9, 5, 11, 3, 5 };
System.out.println("\nOriginal array: "+Arrays.toString(nums));
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:
Java Code Editor:
Improve this sample solution and post your code through Disqus
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.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework