Maximum difference problem GFG
package com.company;
public class Array11 {
// Efficient method
public static int maxDiff(int[] arr) {
int n = arr.length;
int res = arr[1] - arr[0];
int minValue = arr[0];
for (int j = 1; j < n; j++) {
res = Math.max(res, arr[j] - minValue);
minValue = Math.min(minValue, arr[j]);
}
return res;
}
// Maximum difference MY SOLUTION
public static int maxDifference(int[] arr) {
int n = arr.length;
int max = arr[n - 1] - arr[n - 2];
for (int i = n - 1; i >= 0; i--) {
for (int j = i - 1; j >= 0; j--) {
max = Math.max(max, arr[i] - arr[j]);
}
}
return max;
}
public static void main(String[] args) {
int[] array = {2, 3, 10, 6, 4, 8, 100};
System.out.println(maxDiff(array));
}
}
Comments
Post a Comment