查找具有最大值和最小值之间差异的子数组范围正好 K
给定一个长度为N和整数K的数组arr[] ,任务是打印数组的子数组范围(起始索引,结束索引),其中子数组的最大和最小元素之间的差恰好是 K。(基于 1 的索引)
例子:
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 = 2
Input: arr[] = {5, 3, 4, 6, 1, 2}, K = 6
Output: -1
Explanation: There is no such sub array ranges.
方法:解决问题的基本思想是形成所有子数组,并找到每个子数组的最小值和最大值及其差异。请按照以下步骤解决问题。
- 从i = 0 到 N-1遍历数组:
- 从j = i 迭代到 N-1 :
- 在存储从i开始的当前子数组的集合中插入arr[j]当前元素。
- 找到集合的最小值和最大值。
- 获取它们的差值并检查它们的差值是否等于K。
- 如果是,则在答案中推动这个范围。
- 从j = i 迭代到 N-1 :
- 返回范围。
- 如果没有这样的范围,则返回 -1。
下面是上述方法的实现。
C++
// C++ implementation of above approach
#include
using namespace std;
// Function to print index ranges
void printRanges(vector 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 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 Code
int main()
{
vector arr = { 2, 1, 3, 4, 2, 6 };
int N = arr.size();
int K = 2;
// Function call
printRanges(arr, N, K);
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
class GFG {
// Function to print index ranges
static void printRanges(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 s = new HashSet<>();
for (j = i; j < n; j++) {
// Insert current element in set
s.add(arr[j]);
// Calculate max and min for
// any particular index range
int max = Collections.max(s);
int min = Collections.min(s);
// If we get max-min = K
// print 1 based index
if (max - min == K) {
System.out.println( (i + 1) + " " + (j + 1));
f = 1;
}
}
}
// If we didn't find any index ranges
if (f == 0)
System.out.println(-1);
}
// Driver Code
public static void main (String[] args) {
int arr[] = { 2, 1, 3, 4, 2, 6 };
int N = arr.length;
int K = 2;
// Function call
printRanges(arr, N, K);
}
}
// This code is contributed by hrithikgarg03188.
1 3
2 3
3 5
4 5
时间复杂度: O(N 2 * logN)
辅助空间: O(N)