Find Subarray ranges having difference between max and min exactly K
Given an array arr[] of length N and integer K, the task is to print subarray ranges (starting index, ending index) of the array where difference between max and min elements of the subarray is exactly K.( 1-based index )
Examples:
Input: arr[] = {2, 1, 3, 4, 2, 6}, K = 2
Output: (1, 3), (2, 3), (3, 5), (4, 5)
Explanation: In the above array following sub array ranges have max min difference exactly K
(1, 3) => max = 3 and min = 1. Difference = 3 – 1 = 2
(2, 3) => max = 3 and min = 1. Difference = 3 – 1 = 2
(3, 5) => max = 4 and min = 2. Difference = 4 – 2 = 2
(4, 5) => max = 4 and min = 2. Difference = 4 – 2 = 2Input: arr[] = {5, 3, 4, 6, 1, 2}, K = 6
Output: -1
Explanation: There is no such sub array ranges.
Approach: The basic idea to solve the problem is to form all the subarrays and find the minimum and maximum and their difference for each subarray. Follow the steps mentioned below to solve the problem.
- Iterate over the array from i = 0 to N-1:
- Iterate from j = i to N-1:
- Insert arr[j] current element in a set storing the current subarray starting from i.
- Find the minimum and maximum of the set.
- Get their difference and check if their difference is equal to K or not.
- If it is, then push this range in the answer.
- Iterate from j = i to N-1:
- Return the ranges.
- If no such range then return -1.
Below is the implementation of the above approach.
C++
// C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function to print index rangesvoid printRanges(vector<int> arr, int n, int K){ int i, j, f = 0; for (i = 0; i < n; i++) { // Set to store the elements // of a subarray set<int> s; for (j = i; j < n; j++) { // Insert current element in set s.insert(arr[j]); // Calculate max and min for // any particular index range int max = *s.rbegin(); int min = *s.begin(); // If we get max-min = K // print 1 based index if (max - min == K) { cout << i + 1 << " " << j + 1 << "\n"; f = 1; } } } // If we didn't find any index ranges if (f == 0) cout << -1 << endl;} // Driver Codeint main(){ vector<int> arr = { 2, 1, 3, 4, 2, 6 }; int N = arr.size(); int K = 2; // Function call printRanges(arr, N, K); return 0;} |
1 3 2 3 3 5 4 5
Time Complexity: O(N2 * logN)
Auxiliary Space: O(N)

