给定一个由N 个元素组成的数组arr[] ,任务是找到具有奇数乘积的最长子数组的长度。
例子:
Input: arr[] = {3, 5, 2, 1}
Output: 2
Explanation:
Subarrays with consecutive odd elements are {3, 5}, and {1}.
Since, {3, 5} is the longer, the answer is 2.
Input: arr[] = {8, 5, 3, 1, 0}
Output: 3
Explanation:
Longest subarray with odd product is {5, 3, 1}.
方法:
解决问题需要以下观察:
The Product of two odd numbers generates an odd number.
The Product of one odd and one even number generates an even number.
The Product of two even numbers generates an even number.
从上面的观察,我们可以得出结论,数组中连续奇数元素的最长子数组就是所需的答案。
请按照以下步骤解决问题:
- 遍历数组并检查当前元素是偶数还是奇数。
- 如果当前元素为奇数,则将count设置为1并继续增加 count 直到在数组中遇到偶数元素。
- 一旦遇到偶数元素,将计数与ans进行比较并更新ans存储两者的最大值。
- 对剩余的数组重复上述步骤。
- 最后,打印存储在ans 中的值。
下面是上述方法的实现:
C++
// C++ Program to find the longest
// subarray with odd product
#include
using namespace std;
// Function to return length of
// longest subarray with odd product
int Maxlen(int arr[], int n)
{
int ans = 0;
int count = 0;
for (int i = 0; i < n; i++) {
// If even element
// is encountered
if (arr[i] % 2 == 0)
count = 0;
else
count++;
// Update maximum
ans = max(ans, count);
}
return ans;
}
// Driver Code
int main()
{
// int arr[] = { 6, 3, 5, 1 };
int arr[] = { 1, 7, 2 };
int n = sizeof(arr) / sizeof(int);
cout << Maxlen(arr, n) << endl;
return 0;
}
Java
// Java program to find the longest
// subarray with odd product
import java.util.*;
class GFG{
// Function to return length of
// longest subarray with odd product
static int Maxlen(int arr[], int n)
{
int ans = 0;
int count = 0;
for(int i = 0; i < n; i++)
{
// If even element
// is encountered
if (arr[i] % 2 == 0)
count = 0;
else
count++;
// Update maximum
ans = Math.max(ans, count);
}
return ans;
}
// Driver Code
public static void main(String s[])
{
int arr[] = { 1, 7, 2 };
int n = arr.length;
System.out.println(Maxlen(arr, n));
}
}
// This code is contributed by rutvik_56
Python3
# Python3 program to find the longest
# subarray with odd product
# Function to return length of
# longest subarray with odd product
def Maxlen(a, n):
ans = 0
count = 0
for i in range(n):
# If even element
# is encountered
if a[i] % 2 == 0:
count = 0
else:
count += 1
# Update maximum
ans = max(ans, count)
return ans
# Driver code
arr = [ 1, 7, 2 ]
n = len(arr)
print(Maxlen(arr, n))
# This code is contributed by amreshkumar3
C#
// C# program to find the longest
// subarray with odd product
using System;
class GFG{
// Function to return length of
// longest subarray with odd product
static int Maxlen(int []arr, int n)
{
int ans = 0;
int count = 0;
for(int i = 0; i < n; i++)
{
// If even element
// is encountered
if (arr[i] % 2 == 0)
count = 0;
else
count++;
// Update maximum
ans = Math.Max(ans, count);
}
return ans;
}
// Driver Code
public static void Main()
{
int []arr = { 1, 7, 2 };
int n = arr.Length;
Console.WriteLine(Maxlen(arr, n));
}
}
// This code is contributed by amreshkumar3
Javascript
输出:
2
时间复杂度: O(N)
辅助空间: O(1)