📜  长度K的最大偶数和子序列

📅  最后修改于: 2021-05-17 06:32:33             🧑  作者: Mango

给定一个由N个正整数和一个整数K组成的数组arr [] ,任务是找到大小K的任何子序列的最大可能的偶数和。如果找不到大小为K的偶数和子序列,则打印-1

例子:

天真的方法:解决此问题的最简单方法是从给定数组生成大小为K的所有可能子序列,并打印最大可能值,甚至将给定数组的可能子序列求和。

时间复杂度: O(K * N K )
辅助空间: O(K)

高效方法:为了优化上述方法,其思想是将给定数组的所有偶数和奇数存储到两个单独的数组中,并对这两个数组进行排序。最后,使用贪婪技术来计算大小为K的最大和偶子序列。请按照以下步骤解决问题:

  • 初始化一个变量,例如maxSum,以存储给定数组的子序列的最大偶数和。
  • 初始化两个数组,例如Even []Odd [] ,分别存储给定数组的所有偶数和奇数。
  • 遍历给定数组,并将给定数组的所有偶数和奇数分别存储到Even []Odd []数组中。
  • Even []Odd []数组进行排序。
  • 初始化两个变量,例如ij ,分别存储Even []Odd []数组的索引。
  • 遍历偶数[]奇数[]数组并检查以下条件:
    • 如果K%2 == 1则将maxSum的值增加Even [i]
    • 否则,将maxSum的值增加max(Even [i] + Even [i – 1],Odd [j] + Odd [j – 1])
  • 最后,输出maxSum的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find the
// maximum even sum of any
// subsequence of length K
int evenSumK(int arr[], int N, int K)
{
 
    // If count of elements
    // is less than K
    if (K > N) {
        return -1;
    }
 
    // Stores maximum
    // even subsequence sum
    int maxSum = 0;
 
    // Stores Even numbers
    vector Even;
 
    // Stores Odd numbers
    vector Odd;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If current element
        // is an odd number
        if (arr[i] % 2) {
 
            // Insert odd number
            Odd.push_back(arr[i]);
        }
        else {
 
            // Insert even numbers
            Even.push_back(arr[i]);
        }
    }
 
    // Sort Odd[] array
    sort(Odd.begin(), Odd.end());
 
    // Sort Even[] array
    sort(Even.begin(), Even.end());
 
    // Stores current index
    // Of Even[] array
    int i = Even.size() - 1;
 
    // Stores current index
    // Of Odd[] array
    int j = Odd.size() - 1;
 
    while (K > 0) {
 
        // If K is odd
        if (K % 2 == 1) {
 
            // If count of elements
            // in Even[] >= 1
            if (i >= 0) {
 
                // Update maxSum
                maxSum += Even[i];
 
                // Update i
                i--;
            }
 
            // If count of elements
            // in Even[] array is 0.
            else {
                return -1;
            }
 
            // Update K
            K--;
        }
 
        // If count of elements
        // in Even[] and odd[] >= 2
        else if (i >= 1 && j >= 1) {
 
            if (Even[i] + Even[i - 1]
                <= Odd[j] + Odd[j - 1]) {
 
                // Update maxSum
                maxSum += Odd[j] + Odd[j - 1];
 
                // Update j.
                j -= 2;
            }
            else {
 
                // Update maxSum
                maxSum += Even[i] + Even[i - 1];
 
                // Update i
                i -= 2;
            }
 
            // Update K
            K -= 2;
        }
 
        // If count of elements
        // in Even[] array >= 2.
        else if (i >= 1) {
 
            // Update maxSum
            maxSum += Even[i] + Even[i - 1];
 
            // Update i.
            i -= 2;
 
            // Update K.
            K -= 2;
        }
 
        // If count of elements
        // in Odd[] array >= 1
        else if (j >= 1) {
 
            // Update maxSum
            maxSum += Odd[j] + Odd[j - 1];
 
            // Update i.
            j -= 2;
 
            // Update K.
            K -= 2;
        }
    }
 
    return maxSum;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 4, 10, 3, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
    cout << evenSumK(arr, N, K);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG {
 
    // Function to find the
    // maximum even sum of any
    // subsequence of length K
    static int evenSumK(int arr[], int N, int K)
    {
 
        // If count of elements
        // is less than K
        if (K > N) {
            return -1;
        }
 
        // Stores maximum even
        // subsequence sum
        int maxSum = 0;
 
        // Stores Even numbers
        ArrayList Even = new ArrayList();
 
        // Stores Odd numbers
        ArrayList Odd = new ArrayList();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // If current element
            // is an odd number
            if (arr[i] % 2 == 1) {
 
                // Insert odd number
                Odd.add(arr[i]);
            }
            else {
 
                // Insert even numbers
                Even.add(arr[i]);
            }
        }
 
        // Sort Odd[] array
        Collections.sort(Odd);
 
        // Sort Even[] array
        Collections.sort(Even);
 
        // Stores current index
        // Of Even[] array
        int i = Even.size() - 1;
 
        // Stores current index
        // Of Odd[] array
        int j = Odd.size() - 1;
 
        while (K > 0) {
 
            // If K is odd
            if (K % 2 == 1) {
 
                // If count of elements
                // in Even[] >= 1
                if (i >= 0) {
 
                    // Update maxSum
                    maxSum += Even.get(i);
 
                    // Update i
                    i--;
                }
 
                // If count of elements
                // in Even[] array is 0.
                else {
                    return -1;
                }
 
                // Update K
                K--;
            }
 
            // If count of elements
            // in Even[] and odd[] >= 2
            else if (i >= 1 && j >= 1) {
                if (Even.get(i) + Even.get(i - 1)
                    <= Odd.get(j) + Odd.get(j - 1)) {
 
                    // Update maxSum
                    maxSum += Odd.get(j) + Odd.get(j - 1);
 
                    // Update j
                    j -= 2;
                }
                else {
 
                    // Update maxSum
                    maxSum += Even.get(i) + Even.get(i - 1);
 
                    // Update i
                    i -= 2;
                }
 
                // Update K
                K -= 2;
            }
 
            // If count of elements
            // in Even[] array >= 2.
            else if (i >= 1) {
 
                // Update maxSum
                maxSum += Even.get(i) + Even.get(i - 1);
 
                // Update i
                i -= 2;
 
                // Update K
                K -= 2;
            }
 
            // If count of elements
            // in Odd[] array >= 1
            else if (j >= 1) {
 
                // Update maxSum
                maxSum += Odd.get(j) + Odd.get(j - 1);
 
                // Update i.
                j -= 2;
 
                // Update K.
                K -= 2;
            }
        }
        return maxSum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 2, 4, 10, 3, 5 };
        int N = arr.length;
        int K = 3;
 
        System.out.println(evenSumK(arr, N, K));
    }
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach
 
# Function to find the
# maximum even sum of any
# subsequence of length K
 
 
def evenSumK(arr, N, K):
 
    # If count of elements
    # is less than K
    if (K > N):
        return -1
 
    # Stores maximum
    # even subsequence sum
    maxSum = 0
 
    # Stores Even numbers
    Even = []
 
    # Stores Odd numbers
    Odd = []
 
    # Traverse the array
    for i in range(N):
 
        # If current element
        # is an odd number
        if (arr[i] % 2):
 
            # Insert odd number
            Odd.append(arr[i])
 
        else:
 
            # Insert even numbers
            Even.append(arr[i])
 
    # Sort Odd[] array
    Odd.sort(reverse=False)
 
    # Sort Even[] array
    Even.sort(reverse=False)
 
    # Stores current index
    # Of Even[] array
    i = len(Even) - 1
 
    # Stores current index
    # Of Odd[] array
    j = len(Odd) - 1
 
    while (K > 0):
 
        # If K is odd
        if (K % 2 == 1):
 
            # If count of elements
            # in Even[] >= 1
            if (i >= 0):
 
                # Update maxSum
                maxSum += Even[i]
 
                # Update i
                i -= 1
 
            # If count of elements
            # in Even[] array is 0.
            else:
                return -1
 
            # Update K
            K -= 1
 
        # If count of elements
        # in Even[] and odd[] >= 2
        elif (i >= 1 and j >= 1):
            if (Even[i] + Even[i - 1] <=
                    Odd[j] + Odd[j - 1]):
 
                # Update maxSum
                maxSum += Odd[j] + Odd[j - 1]
 
                # Update j.
                j -= 2
 
            else:
 
                # Update maxSum
                maxSum += Even[i] + Even[i - 1]
 
                # Update i
                i -= 2
 
            # Update K
            K -= 2
 
        # If count of elements
        # in Even[] array >= 2.
        elif (i >= 1):
 
            # Update maxSum
            maxSum += Even[i] + Even[i - 1]
 
            # Update i.
            i -= 2
 
            # Update K.
            K -= 2
 
        # If count of elements
        # in Odd[] array >= 2
        elif (j >= 1):
 
            # Update maxSum
            maxSum += Odd[j] + Odd[j - 1]
 
            # Update i.
            j -= 2
 
            # Update K.
            K -= 2
 
    return maxSum
 
 
# Driver Code
if __name__ == '__main__':
 
    arr = [2, 4, 10, 3, 5]
    N = len(arr)
    K = 3
 
    print(evenSumK(arr, N, K))
 
# This code is contributed by ipg2016107


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG {
 
    // Function to find the
    // maximum even sum of any
    // subsequence of length K
    static int evenSumK(int[] arr, int N, int K)
    {
        // If count of elements
        // is less than K
        if (K > N) {
            return -1;
        }
 
        // Stores maximum even
        // subsequence sum
        int maxSum = 0;
 
        // Stores Even numbers
        List Even = new List();
 
        // Stores Odd numbers
        List Odd = new List();
 
        // Traverse the array
        for (int l = 0; l < N; l++) {
            // If current element
            // is an odd number
            if (arr[l] % 2 == 1) {
                // Insert odd number
                Odd.Add(arr[l]);
            }
            else {
                // Insert even numbers
                Even.Add(arr[l]);
            }
        }
 
        // Sort Odd[] array
        Odd.Sort();
 
        // Sort Even[] array
        Even.Sort();
 
        // Stores current index
        // Of Even[] array
        int i = Even.Count - 1;
 
        // Stores current index
        // Of Odd[] array
        int j = Odd.Count - 1;
 
        while (K > 0) {
            // If K is odd
            if (K % 2 == 1) {
                // If count of elements
                // in Even[] >= 1
                if (i >= 0) {
                    // Update maxSum
                    maxSum += Even[i];
 
                    // Update i
                    i--;
                }
 
                // If count of elements
                // in Even[] array is 0.
                else {
                    return -1;
                }
 
                // Update K
                K--;
            }
 
            // If count of elements
            // in Even[] and odd[] >= 2
            else if (i >= 1 && j >= 1) {
                if (Even[i] + Even[i - 1]
                    <= Odd[j] + Odd[j - 1]) {
                    // Update maxSum
                    maxSum += Odd[j] + Odd[j - 1];
 
                    // Update j
                    j -= 2;
                }
                else {
                    // Update maxSum
                    maxSum += Even[i] + Even[i - 1];
 
                    // Update i
                    i -= 2;
                }
 
                // Update K
                K -= 2;
            }
 
            // If count of elements
            // in Even[] array >= 2.
            else if (i >= 1) {
                // Update maxSum
                maxSum += Even[i] + Even[i - 1];
 
                // Update i
                i -= 2;
 
                // Update K
                K -= 2;
            }
 
            // If count of elements
            // in Odd[] array >= 2
            else if (j >= 1) {
                // Update maxSum
                maxSum += Odd[j] + Odd[j - 1];
 
                // Update i.
                j -= 2;
 
                // Update K.
                K -= 2;
            }
        }
        return maxSum;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 2, 4, 10, 3, 5 };
        int N = arr.Length;
        int K = 3;
        Console.WriteLine(evenSumK(arr, N, K));
    }
}
 
// This code is contributed by gauravrajput1


输出
18

时间复杂度: O(N * log N)
辅助空间: O(N)