InterviewSolution
Saved Bookmarks
| 1. |
Write a program for finding the greatest difference between two elements of an array that is in increasing order of elements. |
|
Answer» A SOLUTION for this problem can be achieved with the usage of two loops. Initially, we consider the maximum difference value as the difference between the first two array elements. Later, the elements will be picked one by one in the outer loop and the difference between the picked element and every other array element will be calculated in the inner loop, then that difference will be compared with the maximum difference calculated so far. Program: // Java programclass MaxDiffrence{ /* The function will ASSUME that there will be at least two elements in an array. The function will return a negative value if the array is in decreasing order of sorting. This function will return 0 if elements are equal. */ int maximumDiff(int x[], int size) { int res = x[1] - x[0]; int i, j; for (i = 0; i < size; i++) { for (j = i + 1; j < size; j++) { if (x[j] - x[i] > res) res = x[j] - x[i]; } } return res; } // Driver program for testing above function public static void main(String[] args) { MaxDifference md = new MaxDifference(); int array[] = {2, 3, 90, 10, 120}; System.out.println("Maximum difference between two elements of an array is " + md.maximumDiff(array, 5)); }}Output: Maximum difference between two elements of an array is 118 |
|