Número de subsecuencias con suma par e impar – Part 1

Dada una array, encuentre el número de subsecuencias cuya suma es par y el número de subsecuencias cuya suma es impar.
 

Ejemplo:  

Entrada: arr[] = {1, 2, 2, 3} 
Salida: EvenSum = 7, OddSum = 8 
Hay  2^{N}-1     posibles subsecuencias. 
Las subsecuencias con suma par son 
1) {1, 3} Suma = 4 
2) {1, 2, 2, 3} Suma = 8 
3) {1, 2, 3} Suma = 6 (De índice 1) 
4) { 1, 2, 3} Suma = 6 (De índice 2) 
5) {2} Suma = 2 (De índice 1) 
6) {2, 2} Suma = 4 
7) {2} Suma = 2 (De índice 2) 
y el resto de la subsecuencia es de suma impar.

Entrada: arr[] = { 2, 2, 2, 2 } 
Salida: EvenSum = 15, OddSum = 0  

Enfoque ingenuo
un enfoque simple es generar todas las subsecuencias posibles de forma recursiva y contar el número de subsecuencias con una suma par y luego restar del total de subsecuencias y el número será de subsecuencias impares. La complejidad temporal de este enfoque será  O(2^{N}).
 

Mejor enfoque
un mejor enfoque será el uso de la programación dinámica

  • Estaríamos calculando el recuento de subsecuencias pares a medida que iteramos a través de la array. creamos 2 arreglos countODD[N] y countEVEN[N], donde countODD[i] denota el número de subsecuencias con suma impar en el rango  (0, yo)     y countEVEN[i] denota el número de subsecuencias con suma par en el rango (0, yo)
  • Si estamos en la posición i, y el número es IMPAR , entonces el número total de subsecuencias con una suma par sería 
    • Para countEVEN[i] , el i-ésimo número no está emparejado con ninguna otra subsecuencia (es decir, subsecuencias pares hasta la  (i-1)     posición) + el i- ésimo número está emparejado con todas las demás subsecuencias impares hasta la  (i-1)     posición (impar+impar=par)
    • Para countODD[i] , el i-ésimo número no está emparejado con ninguna otra subsecuencia (es decir, subsecuencias impares hasta la  (i-1)     posición) + el i- ésimo número está emparejado con todas las demás subsecuencias pares hasta la  (i-1)     posición (impar+par=impar) + una subsecuencia con solo 1 elemento, es decir, el i-ésimo número en sí mismo
  • Si estamos en la posición i, y el número es PAR , entonces el número total de subsecuencias con una suma par sería
    • Para countEVEN[i] , el i-ésimo número no está emparejado con ninguna otra subsecuencia (es decir, subsecuencias pares hasta la  (i-1)     posición) + el i-ésimo número está emparejado con todas las demás subsecuencias pares hasta la  (i-1)     posición (par+par=par) + una subsecuencia con solo 1 elemento, es decir, el i-ésimo número en sí mismo
    • Para countODD[i] , el i-ésimo número no está emparejado con ninguna otra subsecuencia (es decir, subsecuencias impares hasta la  (i-1)     posición) + el i-ésimo número está emparejado con todas las demás subsecuencias impares hasta la  (i-1)     posición (par+impar=impar)

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ implementation
#include <bits/stdc++.h>
using namespace std;
 
// returns the count of odd and
// even subsequences
pair<int, int> countSum(int arr[], int n)
{
    int result = 0;
 
    // Arrays to store the count of even
    // subsequences and odd subsequences
    int countODD[n + 1], countEVEN[n + 1];
 
    // Initialising countEVEN[0] and countODD[0] to 0
    // since as there is no subsequence before the
    // iteration with even or odd count.
    countODD[0] = 0;
    countEVEN[0] = 0;
 
    // Find sum of all subsequences with even count
    // and odd count storing them as we iterate.
 
    // Here countEVEN[i] denotes count of
    // even subsequences till i
 
    // Here countODD[i] denotes count of
    // odd subsequences till i
 
    for (int i = 1; i <= n; i++) {
 
        // if the number is even
        if (arr[i - 1] % 2 == 0) {
            countEVEN[i] = countEVEN[i - 1]
                           + countEVEN[i - 1] + 1;
 
            countODD[i] = countODD[i - 1]
                          + countODD[i - 1];
        }
        // if the number is odd
        else {
            countEVEN[i] = countEVEN[i - 1]
                           + countODD[i - 1];
 
            countODD[i] = countODD[i - 1]
                          + countEVEN[i - 1] + 1;
        }
    }
 
    return { countEVEN[n], countODD[n] };
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Calling the function
 
    pair<int, int> ans = countSum(arr, n);
 
    cout << "EvenSum = " << ans.first;
    cout << " OddSum = " << ans.second;
 
    return 0;
}

Java

// Java implementation to find the number
// of Subsequences with Even and Odd Sum
import java.util.*;
import java.lang.*;
 
class GFG
{
    public static int[] countSum(int arr[], int n)
    {
        int result = 0;
 
        // Arrays to store the count of even
        // subsequences and odd subsequences
        int[] countODD = new int[n + 1];
        int[] countEVEN = new int[n + 1];
         
        // Initialising countEVEN[0] and countODD[0] to 0
        // since as there is no subsequence before the
        // iteration with even or odd count.
        countODD[0] = 0;
        countEVEN[0] = 0;
         
        // Find sum of all subsequences with even count
        // and odd count storing them as we iterate.
     
        // Here countEVEN[i] denotes count of
        // even subsequences till i
     
        // Here countODD[i] denotes count of
        // odd subsequences till i
        for (int i = 1; i <= n; i++)
        {
 
            // if the number is even
            if (arr[i - 1] % 2 == 0)
            {
                countEVEN[i] = countEVEN[i - 1] +
                               countEVEN[i - 1] + 1;
     
                countODD[i] = countODD[i - 1] +
                              countODD[i - 1];
            }
             
            // if the number is odd
            else
            {
                countEVEN[i] = countEVEN[i - 1] +
                               countODD[i - 1];
     
                countODD[i] = countODD[i - 1] +
                              countEVEN[i - 1] + 1;
            }
        }
         
        int[] ans = new int[2];
        ans[0] = countEVEN[n];
        ans[1] = countODD[n];
        return ans;
    }
 
    // Driver Code
    public static void main (String[] args)
    {
        int[] arr = new int[]{ 1, 2, 2, 3 };
        int n = 4;
        int[] ans = countSum(arr, n);
        System.out.println("EvenSum = " + ans[0]);
        System.out.println("OddSum = " + ans[1]);
    }
}
 
// This code is contributed by Shivam Sharma

Python3

# Python3 implementation of above approach
 
# Returns the count of odd and
# even subsequences
def countSum(arr, n):
     
    result = 0
 
    # Variables to store the count of even
    # subsequences and odd subsequences
 
    # Initialising count_even and count_odd to 0
    # since as there is no subsequence before the
    # iteration with even or odd count.
    count_odd = 0
    count_even = 0
 
    # Find sum of all subsequences with even count
    # and odd count and storing them as we iterate.
 
    for i in range(n):
 
        # if the number is even
        if arr[i - 1] % 2 == 0:
            count_even = count_even + count_even + 1
            count_odd = count_odd + count_odd
 
        # if the number is odd
        else:
            temp = count_even
            count_even = count_even + count_odd
            count_odd = count_odd + temp + 1
         
    return [count_even, count_odd]
 
# Driver code
arr = [ 1, 2, 2, 3 ]
n = len(arr)
 
# Calling the function
ans = countSum(arr, n)
 
print('EvenSum =', ans[0],
      'OddSum =', ans[1])
 
# This code is contributed
# by Saurabh_shukla

C#

// C# implementation to find the number
// of Subsequences with Even and Odd Sum
using System;
class GFG
{
    public static int[] countSum(int []arr, int n)
    {
 
        // Arrays to store the count of even
        // subsequences and odd subsequences
        int[] countODD = new int[n + 1];
        int[] countEVEN = new int[n + 1];
         
        // Initialising countEVEN[0] and countODD[0] to 0
        // since as there is no subsequence before the
        // iteration with even or odd count.
        countODD[0] = 0;
        countEVEN[0] = 0;
         
        // Find sum of all subsequences with even count
        // and odd count storing them as we iterate.
     
        // Here countEVEN[i] denotes count of
        // even subsequences till i
     
        // Here countODD[i] denotes count of
        // odd subsequences till i
        for (int i = 1; i <= n; i++)
        {
 
            // if the number is even
            if (arr[i - 1] % 2 == 0)
            {
                countEVEN[i] = countEVEN[i - 1] +
                               countEVEN[i - 1] + 1;
     
                countODD[i] = countODD[i - 1] +
                              countODD[i - 1];
            }
             
            // if the number is odd
            else
            {
                countEVEN[i] = countEVEN[i - 1] +
                               countODD[i - 1];
     
                countODD[i] = countODD[i - 1] +
                              countEVEN[i - 1] + 1;
            }
        }
         
        int[] ans = new int[2];
        ans[0] = countEVEN[n];
        ans[1] = countODD[n];
        return ans;
    }
 
    // Driver Code
    public static void Main (String[] args)
    {
        int[] arr = new int[]{ 1, 2, 2, 3 };
        int n = 4;
        int[] ans = countSum(arr, n);
        Console.WriteLine("EvenSum = " + ans[0]);
        Console.WriteLine("OddSum = " + ans[1]);
    }
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
  
// JavaScript implementation to find the number
// of Subsequences with Even and Odd Sum
function countSum(arr, n)
{
    // Arrays to store the count of even
    // subsequences and odd subsequences
    var countODD = Array(n+1).fill(0);
    var countEVEN = Array(n+1).fill(0);
     
    // Initialising countEVEN[0] and countODD[0] to 0
    // since as there is no subsequence before the
    // iteration with even or odd count.
    countODD[0] = 0;
    countEVEN[0] = 0;
     
    // Find sum of all subsequences with even count
    // and odd count storing them as we iterate.
 
    // Here countEVEN[i] denotes count of
    // even subsequences till i
 
    // Here countODD[i] denotes count of
    // odd subsequences till i
    for (var i = 1; i <= n; i++)
    {
        // if the number is even
        if (arr[i - 1] % 2 == 0)
        {
            countEVEN[i] = countEVEN[i - 1] +
                           countEVEN[i - 1] + 1;
 
            countODD[i] = countODD[i - 1] +
                          countODD[i - 1];
        }
         
        // if the number is odd
        else
        {
            countEVEN[i] = countEVEN[i - 1] +
                           countODD[i - 1];
 
            countODD[i] = countODD[i - 1] +
                          countEVEN[i - 1] + 1;
        }
    }
     
    var ans = [0,0];
    ans[0] = countEVEN[n];
    ans[1] = countODD[n];
    return ans;
}
// Driver Code
var arr = [ 1, 2, 2, 3 ];
var n = 4;
var ans = countSum(arr, n);
document.write("EvenSum = " + ans[0]);
document.write(" OddSum = " + ans[1]);
 
 
</script>
Producción: 

EvenSum = 7 OddSum = 8

 

Complejidad temporal: O(N)
Complejidad espacial: O(N) donde N es el número de elementos en la array.
 

Enfoque eficiente
en lugar de hacer arrays countEVEN[N] y countODD[N], solo necesitamos las variables count_even y count_odd y cambiarlas de la misma manera que lo hicimos antes. 
A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ implementation
#include <bits/stdc++.h>
using namespace std;
 
// Returns the count of odd and
// even subsequences
pair<int, int> countSum(int arr[], int n)
{
    int result = 0;
 
    // Variables to store the count of even
    // subsequences and odd subsequences
    int count_odd, count_even;
 
    // Initialising count_even and count_odd to 0
    // since as there is no subsequence before the
    // iteration with even or odd count.
    count_odd = 0;
    count_even = 0;
 
    // Find sum of all subsequences with even count
    // and odd count and storing them as we iterate.
 
    for (int i = 1; i <= n; i++) {
 
        // if the number is even
        if (arr[i - 1] % 2 == 0) {
            count_even = count_even + count_even + 1;
            count_odd = count_odd + count_odd;
        }
 
        // if the number is odd
        else {
            int temp = count_even;
            count_even = count_even + count_odd;
            count_odd = count_odd + temp + 1;
        }
    }
 
    return { count_even, count_odd };
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Calling the function
 
    pair<int, int> ans = countSum(arr, n);
 
    cout << "EvenSum = " << ans.first;
    cout << " OddSum = " << ans.second;
 
    return 0;
}

Java

// Java program to get minimum cost to sort
// strings by reversal operation
class GFG
{
 
static class pair
{
    int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Returns the count of odd and
// even subsequences
static pair countSum(int arr[], int n)
{
    int result = 0;
 
    // Variables to store the count of even
    // subsequences and odd subsequences
    int count_odd, count_even;
 
    // Initialising count_even and count_odd to 0
    // since as there is no subsequence before the
    // iteration with even or odd count.
    count_odd = 0;
    count_even = 0;
 
    // Find sum of all subsequences with even count
    // and odd count and storing them as we iterate.
    for (int i = 1; i <= n; i++)
    {
 
        // if the number is even
        if (arr[i - 1] % 2 == 0)
        {
            count_even = count_even + count_even + 1;
            count_odd = count_odd + count_odd;
        }
 
        // if the number is odd
        else
        {
            int temp = count_even;
            count_even = count_even + count_odd;
            count_odd = count_odd + temp + 1;
        }
    }
    return new pair(count_even, count_odd );
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 2, 3 };
    int n = arr.length;
 
    // Calling the function
 
    pair ans = countSum(arr, n);
 
    System.out.print("EvenSum = " + ans.first);
    System.out.print(" OddSum = " + ans.second);
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 implementation of above approach
 
# Returns the count of odd and
# even subsequences
def countSum(arr, n):
    result = 0
     
    # Variables to store the count of even
    # subsequences and odd subsequences
    # Initialising count_even and count_odd to 0
    # since as there is no subsequence before the
    # iteration with even or odd count.
    count_odd = 0
    count_even = 0
 
    # Find sum of all subsequences with even count
    # and odd count and storing them as we iterate.
 
    for i in range(1, n + 1):
         
        # if the number is even
        if (arr[i - 1] % 2 == 0):
            count_even = count_even + count_even + 1
            count_odd = count_odd + count_odd
 
        # if the number is odd
        else:
            temp = count_even
            count_even = count_even + count_odd
            count_odd = count_odd + temp + 1
 
    return (count_even, count_odd)
     
# Driver code
arr = [1, 2, 2, 3];
n = len(arr)
 
# Calling the function
count_even, count_odd = countSum(arr, n);
 
print("EvenSum = ", count_even,
      " OddSum = ", count_odd)
       
# This code is contributed
# by ANKITKUMAR34

C#

// C# program to get minimum cost to sort
// strings by reversal operation
using System;
     
class GFG
{
 
public class pair
{
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Returns the count of odd and
// even subsequences
static pair countSum(int []arr, int n)
{
    // Variables to store the count of even
    // subsequences and odd subsequences
    int count_odd, count_even;
 
    // Initialising count_even and count_odd to 0
    // since as there is no subsequence before the
    // iteration with even or odd count.
    count_odd = 0;
    count_even = 0;
 
    // Find sum of all subsequences with even count
    // and odd count and storing them as we iterate.
    for (int i = 1; i <= n; i++)
    {
 
        // if the number is even
        if (arr[i - 1] % 2 == 0)
        {
            count_even = count_even + count_even + 1;
            count_odd = count_odd + count_odd;
        }
 
        // if the number is odd
        else
        {
            int temp = count_even;
            count_even = count_even + count_odd;
            count_odd = count_odd + temp + 1;
        }
    }
    return new pair(count_even, count_odd );
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 2, 3 };
    int n = arr.Length;
 
    // Calling the function
 
    pair ans = countSum(arr, n);
 
    Console.Write("EvenSum = " + ans.first);
    Console.Write(" OddSum = " + ans.second);
}
}
 
// This code is contributed by PrinciRaj1992

Javascript

<script>
 
// Java program to get minimum cost to sort
// strings by reversal operation
var first, second;
function pair( first,  second)
{
    this.first = first;
    this.second = second;
}
 
// Returns the count of odd and
// even subsequences
function countSum(arr, n)
{
    var result = 0;
 
    // Variables to store the count of even
    // subsequences and odd subsequences
    var count_odd, count_even;
 
    // Initialising count_even and count_odd to 0
    // since as there is no subsequence before the
    // iteration with even or odd count.
    count_odd = 0;
    count_even = 0;
 
    // Find sum of all subsequences with even count
    // and odd count and storing them as we iterate.
    for (var i = 1; i <= n; i++)
    {
 
        // if the number is even
        if (arr[i - 1] % 2 == 0)
        {
            count_even = count_even + count_even + 1;
            count_odd = count_odd + count_odd;
        }
 
        // if the number is odd
        else
        {
            var temp = count_even;
            count_even = count_even + count_odd;
            count_odd = count_odd + temp + 1;
        }
    }
    return new pair(count_even, count_odd );
}
 
// Driver code
var arr = [ 1, 2, 2, 3 ];
var n = arr.length;
 
// Calling the function
 
var ans = countSum(arr, n);
 
document.write("EvenSum = " + ans.first);
document.write(" OddSum = " + ans.second);
 
// This code is contributed by shivanisinghss2110
 
</script>
Producción: 

EvenSum = 7 OddSum = 8

 

Complejidad temporal: O(N)
Complejidad espacial: O(1) , donde N es el número de elementos en la array.
 

Publicación traducida automáticamente

Artículo escrito por mehul_02 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *