You are given an array of size and an integer . Your task is to find the largest subarray of the provided array such that the absolute difference between any two elements in the subarray is less than or equal to .
Let and be the maximum and minimum value in the selected largest subarray. Now, must hold.
Print the length of the largest subarray.
Example:
Input: n=5,k=10,a[] = { 2, 30, 25, 21, 15 };
Output: 3
Approach
Java
public class MaximumRange {public static void main(String[] args) {int n = 5;int k = 10;int a[] = { 2, 30, 25, 21, 15 };int ws = 0;int min = 0;int max = 0;int ans = 1;for (int we = 1; we < n; we++) {if (a[max] < a[we]) {max = we;if (a[max] - a[min] > k) {int mn = we;int i;for (i = we; i >= ws && a[max] - a[i] <= k; i--) {if (a[mn] > a[i])mn = i;}min = mn;ws = i + 1;}} else if (a[min] > a[we]) {min = we;if (a[max] - a[min] > k) {int mx = we;int i;for (i = we; i >= ws && a[i] - a[min] <= k; i--) {if (a[mx] < a[i])mx = i;}max = mx;ws = i + 1;}}ans = Math.max(ans, we - ws + 1);}System.out.println(ans);}}
No comments:
Post a Comment