📌  相关文章
📜  奇数和偶数元素数相等的最长子数组的长度

📅  最后修改于: 2021-06-26 16:42:21             🧑  作者: Mango

给定一个整数数组arr [] ,任务是查找具有相等数量的奇数和偶数元素的最长子数组的长度。

例子:

天真的方法:一种简单的解决方案是一一考虑所有子数组,并检查子数组中偶数和奇数元素的数量,然后从这些子数组中找出最大值。
时间复杂度: O(N 2 )

高效方法:想法是将奇数元素视为1,将偶数元素视为-1,并返回总和等于0的最长子数组的长度。使用此方法可以找到具有给定总和的子数组。
时间复杂度: O(N)

下面是上述方法的实现:

C++
// C++ program to find the length
// of the longest sub-array with an
// equal number of odd and even elements
#include 
using namespace std;
  
// Function that returns the length of
// the longest sub-array with an equal
// number of odd and even elements
int maxSubarrayLength(int* A, int N)
{
    // Initialize variable to store result
    int maxLen = 0;
  
    // Initialize variable to store sum
    int curr_sum = 0;
  
    // Create an empty map to store
    // index of the sum
    unordered_map hash;
  
    // Loop through the array
    for (int i = 0; i < N; i++) {
        if (A[i] % 2 == 0)
            curr_sum -= 1;
        else
            curr_sum += 1;
  
        // Check if number of even and
        // odd elements are equal
        if (curr_sum == 0)
            maxLen = max(maxLen, i + 1);
  
        // If curr_sum already exists in map
        // we have a subarray with 0 sum, i.e,
        // equal number of odd and even number
        if (hash.find(curr_sum) != hash.end())
            maxLen = max(maxLen,
                        i - hash[curr_sum]);
  
        // Store the index of the sum
        else
            hash[curr_sum] = i;
    }
    return maxLen;
}
  
// Driver Code
int main()
{
    int arr[] = { 12, 4, 7, 8, 9, 2,
                        11, 0, 2, 13 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << maxSubarrayLength(arr, n);
  
    return 0;
}


Java
// Java program to find the length
// of the longest sub-array with an
// equal number of odd and even elements
import java.util.*;
  
class GFG
{
  
// Function that returns the length of
// the longest sub-array with an equal
// number of odd and even elements
static int maxSubarrayLength(int []A, int N)
{
    // Initialize variable to store result
    int maxLen = 0;
  
    // Initialize variable to store sum
    int curr_sum = 0;
  
    // Create an empty map to store
    // index of the sum
    HashMap hash = new HashMap();
  
    // Loop through the array
    for (int i = 0; i < N; i++)
    {
        if (A[i] % 2 == 0)
            curr_sum -= 1;
        else
            curr_sum += 1;
  
        // Check if number of even and
        // odd elements are equal
        if (curr_sum == 0)
            maxLen = Math.max(maxLen, i + 1);
  
        // If curr_sum already exists in map
        // we have a subarray with 0 sum, i.e,
        // equal number of odd and even number
        if (hash.containsKey(curr_sum))
            maxLen = Math.max(maxLen,
                        i - hash.get(curr_sum));
  
        // Store the index of the sum
        else {
            hash.put(curr_sum, i);
        }
    }
    return maxLen;
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 12, 4, 7, 8, 9, 2,
                        11, 0, 2, 13 };
    int n = arr.length;
  
    System.out.print(maxSubarrayLength(arr, n));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find the length 
# of the longest sub-array with an 
# equal number of odd and even elements 
  
# Function that returns the length of 
# the longest sub-array with an equal 
# number of odd and even elements 
def maxSubarrayLength(A, N) : 
  
    # Initialize variable to store result 
    maxLen = 0; 
  
    # Initialize variable to store sum 
    curr_sum = 0; 
  
    # Create an empty map to store 
    # index of the sum 
    hash = {}; 
  
    # Loop through the array 
    for i in range(N) :
        if (A[i] % 2 == 0) :
            curr_sum -= 1; 
        else :
            curr_sum += 1; 
  
        # Check if number of even and 
        # odd elements are equal 
        if (curr_sum == 0) :
            maxLen = max(maxLen, i + 1); 
  
        # If curr_sum already exists in map 
        # we have a subarray with 0 sum, i.e, 
        # equal number of odd and even number 
        if curr_sum in hash :
            maxLen = max(maxLen, i - hash[curr_sum]); 
  
        # Store the index of the sum 
        else :
            hash[curr_sum] = i; 
      
    return maxLen; 
  
# Driver Code 
if __name__ == "__main__" : 
  
    arr = [ 12, 4, 7, 8, 9, 2, 11, 0, 2, 13 ]; 
    n = len(arr); 
  
    print(maxSubarrayLength(arr, n)); 
  
# This code is contributed by AnkitRai01


C#
// C# program to find the length
// of the longest sub-array with an
// equal number of odd and even elements
using System;
using System.Collections.Generic;
  
class GFG
{
  
// Function that returns the length of
// the longest sub-array with an equal
// number of odd and even elements
static int maxSubarrayLength(int []A, int N)
{
    // Initialize variable to store result
    int maxLen = 0;
  
    // Initialize variable to store sum
    int curr_sum = 0;
  
    // Create an empty map to store
    // index of the sum
    Dictionary hash = new Dictionary();
  
    // Loop through the array
    for (int i = 0; i < N; i++)
    {
        if (A[i] % 2 == 0)
            curr_sum -= 1;
        else
            curr_sum += 1;
  
        // Check if number of even and
        // odd elements are equal
        if (curr_sum == 0)
            maxLen = Math.Max(maxLen, i + 1);
  
        // If curr_sum already exists in map
        // we have a subarray with 0 sum, i.e,
        // equal number of odd and even number
        if (hash.ContainsKey(curr_sum))
            maxLen = Math.Max(maxLen,
                        i - hash[curr_sum]);
  
        // Store the index of the sum
        else {
            hash.Add(curr_sum, i);
        }
    }
    return maxLen;
}
  
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 12, 4, 7, 8, 9, 2,
                        11, 0, 2, 13 };
    int n = arr.Length;
    Console.Write(maxSubarrayLength(arr, n));
}
}
  
// This code is contributed by 29AjayKumar


输出:
8

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。