给定N个数组,仅包含正数和负数。任务是找到阵列中存在的最长的交替子阵列(意味着负-正-负或正-负-正-正)子阵列的长度。
例子:
Input: a[] = {-5, -1, -1, 2, -2, -3}
Output: 3
The subarray {-1, 2, -2}
Input: a[] = {1, -5, 1, -5}
Output: 4
方法:按照以下步骤解决问题:
- 最初将cnt初始化为1。
- 在数组元素之间进行迭代,检查其是否具有备用符号。
- 如果cnt有备用符号,则将cnt增加1。
- 如果没有备用符号,请用1重新初始化cnt。
下面是上述方法的实现:
C++
// C++ program to find the longest alternating
// subarray in an array of N number
#include
using namespace std;
// Function to find the longest subarray
int longestAlternatingSubarray(int a[], int n)
{
// Length of longest alternating
int longest = 1;
int cnt = 1;
// Iterate in the array
for (int i = 1; i < n; i++) {
// Check for alternate
if (a[i] * a[i - 1] < 0) {
cnt++;
longest = max(longest, cnt);
}
else
cnt = 1;
}
return longest;
}
/* Driver program to test above functions*/
int main()
{
int a[] = { -5, -1, -1, 2, -2, -3 };
int n = sizeof(a) / sizeof(a[0]);
// Function to find the longest subarray
cout << longestAlternatingSubarray(a, n);
return 0;
}
Java
// Java program to find the longest alternating
// subarray in an array of N number
class GFG
{
// Function to find the longest subarray
static int longestAlternatingSubarray(int a[], int n)
{
// Length of longest alternating
int longest = 1;
int cnt = 1;
// Iterate in the array
for (int i = 1; i < n; i++)
{
// Check for alternate
if (a[i] * a[i - 1] < 0)
{
cnt++;
longest = Math.max(longest, cnt);
}
else
cnt = 1;
}
return longest;
}
/* Driver program to test above functions*/
public static void main (String[] args)
{
int a[] = { -5, -1, -1, 2, -2, -3 };
int n = a.length ;
// Function to find the longest subarray
System.out.println(longestAlternatingSubarray(a, n));
}
}
// This code is contributed by Ryuga
Python 3
# Python3 program to find the longest alternating
# subarray in an array of N number
# Function to find the longest subarray
def longestAlternatingSubarray(a, n):
# Length of longest alternating
longest = 1
cnt = 1
# Iterate in the array
i = 1
while i < n:
# Check for alternate
if (a[i] * a[i - 1] < 0):
cnt = cnt + 1
longest = max(longest, cnt)
else:
cnt = 1
i = i + 1
return longest
# Driver Code
a = [ -5, -1, -1, 2, -2, -3 ]
n = len(a)
# Function to find the longest subarray
print(longestAlternatingSubarray(a, n))
# This code is contributed
# by shashank_sharma
C#
// C# program to find the longest alternating
// subarray in an array of N number
using System;
class GFG
{
// Function to find the longest subarray
static int longestAlternatingSubarray(int []a,
int n)
{
// Length of longest alternating
int longest = 1;
int cnt = 1;
// Iterate in the array
for (int i = 1; i < n; i++)
{
// Check for alternate
if (a[i] * a[i - 1] < 0)
{
cnt++;
longest = Math.Max(longest, cnt);
}
else
cnt = 1;
}
return longest;
}
// Driver Code
public static void Main()
{
int []a = { -5, -1, -1, 2, -2, -3 };
int n = a.Length;
// Function to find the longest subarray
Console.Write(longestAlternatingSubarray(a, n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
Javascript
输出:
3