给定一个数组arr[] ,任务是找到一个最大和最小元素之差大于或等于子数组长度的子数组。如果不存在这样的子数组,则打印-1 。
例子:
Input: arr[] = {3, 7, 5, 1}
Output: 3 7
|3 – 7| > length({3, 7}) i.e. 4 ≥ 2
Input: arr[] = {1, 2, 3, 4, 5}
Output: -1
There is no such subarray that meets the criteria.
天真的方法:找到所有可能有至少两个元素的子数组,然后检查满足给定条件的每个子数组,即 max(subarray) – min(subarray) ≥ len(subarray)
高效的方法:找出长度为2的子数组,其中只有两个元素之间的绝对差大于或等于2。这将涵盖几乎所有情况,因为没有这样的子数组时只有三种情况:
- 当数组的长度为0 时。
- 当数组中的所有元素都相等时。
- 当数组中每两个连续元素的绝对差为 0 或 1 时。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the required subarray
void findSubArr(int arr[], int n)
{
// For every two consecutive element subarray
for (int i = 0; i < n - 1; i++) {
// If the current pair of consecutive
// elements satisfies the given condition
if (abs(arr[i] - arr[i + 1]) >= 2) {
cout << arr[i] << " " << arr[i + 1];
return;
}
}
// No such subarray found
cout << -1;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 4, 6, 7 };
int n = sizeof(arr) / sizeof(int);
findSubArr(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to find the required subarray
static void findSubArr(int arr[], int n)
{
// For every two consecutive element subarray
for (int i = 0; i < n - 1; i++)
{
// If the current pair of consecutive
// elements satisfies the given condition
if (Math.abs(arr[i] - arr[i + 1]) >= 2)
{
System.out.print(arr[i] + " " + arr[i + 1]);
return;
}
}
// No such subarray found
System.out.print(-1);
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 1, 2, 4, 6, 7 };
int n = arr.length;
findSubArr(arr, n);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to find the required subarray
def findSubArr(arr, n) :
# For every two consecutive element subarray
for i in range(n - 1) :
# If the current pair of consecutive
# elements satisfies the given condition
if (abs(arr[i] - arr[i + 1]) >= 2) :
print(arr[i] ,arr[i + 1],end="");
return;
# No such subarray found
print(-1);
# Driver code
if __name__ == "__main__" :
arr = [ 1, 2, 4, 6, 7 ];
n = len(arr);
findSubArr(arr, n);
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find the required subarray
static void findSubArr(int []arr, int n)
{
// For every two consecutive element subarray
for (int i = 0; i < n - 1; i++)
{
// If the current pair of consecutive
// elements satisfies the given condition
if (Math.Abs(arr[i] - arr[i + 1]) >= 2)
{
Console.Write(arr[i] + " " + arr[i + 1]);
return;
}
}
// No such subarray found
Console.Write(-1);
}
// Driver code
public static void Main()
{
int []arr = { 1, 2, 4, 6, 7 };
int n = arr.Length;
findSubArr(arr, n);
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
2 4
时间复杂度: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live