📌  相关文章
📜  分割一个数组以最大化不等于K的奇数和偶数元素数目相等的子数组

📅  最后修改于: 2021-05-04 10:21:33             🧑  作者: Mango

给定大小为N且整数K的数组arr [] ,任务是将给定数组拆分为具有相等数量的偶数和奇数元素的最大可能子数组,以使拆分数组的成本不超过K。

例子:

天真的方法:解决此问题的最简单方法如下:

  1. 在每个索引处拆分数组,然后检查开销是否小于K。
  2. 如果代价小于K ,则检查子数组中奇数和偶数元素的数量是否相等。
  3. 现在,通过重复相同的步骤来检查是否可以进行其他拆分。
  4. 检查所有可能的分割后,打印最小成本,总和小于K。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:想法是维护计数器,该计数器在数组中存储偶数和奇数。步骤如下:

  1. 初始化一个数组(例如poss [] ),该数组存储所有可能的拆分的成本。
  2. 遍历数组arr [] 。对于每个索引,检查直到该索引的子数组和从下一个索引开始的子数组的奇数和偶数元素计数是否相等。
  3. 如果满足以上条件,则可以拆分。将与此拆分相关的成本存储在poss []中
  4. 对数组中的所有元素重复上述步骤,并存储每次拆分的成本。
  5. 可以通过abs(arr [i + 1] – arr [i])获得索引i处的拆分成本。
  6. 现在,为了找到可能的拆分的最大数量,对包含每个可能的拆分成本的poss []数组进行排序。
  7. 现在,从poss []中选择总和小于或等于K的所有最小成本。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
  
// Function to find the cost of
// splitting the arrays into subarray
// with cost less than K
int make_cuts(int arr[], int n, int K)
{
    // Store the possible splits
    int ans = 0;
  
    // Stores the cost of each split
    vector poss;
  
    // Stores the count of even numbers
    int ce = 0;
  
    // Stores the count
    // of odd numbers
    int co = 0;
  
    for (int x = 0; x < n - 1; x++) {
  
        // Count of odd & even elements
        if (arr[x] % 2 == 0)
            ce++;
        else
            co++;
  
        // Check the required conditions
        // for a valid split
        if (ce == co && co > 0
            && ce > 0) {
            poss.push_back(
                abs(arr[x]
                    - arr[x + 1]));
        }
    }
  
    // Sort the cost of splits
    sort(poss.begin(), poss.end());
  
    // Find the minimum split costs
    // adding up to sum less than K
    for (int x : poss) {
        if (K >= x) {
            ans++;
            K -= x;
        }
        else
            break;
    }
    return ans;
}
  
// Driver Code
int main()
{
    // Given array and K
    int N = 6;
    int K = 4;
  
    int arr[] = { 1, 2, 5, 10, 15, 20 };
  
    // Function Call
    cout << make_cuts(arr, N, K);
}


Java
// Java program for the above approach
import java.util.*;
  
class GFG{
  
// Function to find the cost of
// splitting the arrays into subarray
// with cost less than K
static int make_cuts(int arr[], int n, int K)
{
      
    // Store the possible splits
    int ans = 0;
  
    // Stores the cost of each split
    Vector poss = new Vector();
  
    // Stores the count of even numbers
    int ce = 0;
  
    // Stores the count
    // of odd numbers
    int co = 0;
  
    for(int x = 0; x < n - 1; x++)
    {
          
        // Count of odd & even elements
        if (arr[x] % 2 == 0)
            ce++;
        else
            co++;
              
        // Check the required conditions
        // for a valid split
        if (ce == co && co > 0 && ce > 0)
        {
            poss.add(Math.abs(arr[x] - 
                              arr[x + 1]));
        }
    }
  
    // Sort the cost of splits
    Collections.sort(poss);
  
    // Find the minimum split costs
    // adding up to sum less than K
    for(int x : poss)
    {
        if (K >= x) 
        {
            ans++;
            K -= x;
        }
        else
            break;
    }
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
      
    // Given array and K
    int N = 6;
    int K = 4;
  
    int arr[] = { 1, 2, 5, 10, 15, 20 };
  
    // Function call
    System.out.print(make_cuts(arr, N, K));
}
}
  
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach 
  
# Function to find the cost of
# splitting the arrays into subarray
# with cost less than K
def make_cuts(arr, n, K):
  
    # Store the possible splits
    ans = 0
  
    # Stores the cost of each split
    poss = []
  
    # Stores the count of even numbers
    ce = 0
  
    # Stores the count
    # of odd numbers
    co = 0
  
    for x in range(n - 1):
  
        # Count of odd & even elements
        if(arr[x] % 2 == 0):
            ce += 1
        else:
            co += 1
  
        # Check the required conditions
        # for a valid split
        if(ce == co and co > 0 and ce > 0):
            poss.append(abs(arr[x] - 
                            arr[x + 1]))
  
    # Sort the cost of splits
    poss.sort()
  
    # Find the minimum split costs
    # adding up to sum less than K
    for x in poss:
        if (K >= x):
            ans += 1
            K -= x
        else:
            break
  
    return ans
  
# Driver Code
  
# Given array and K
N = 6
K = 4
  
arr = [ 1, 2, 5, 10, 15, 20 ]
  
# Function call
print(make_cuts(arr, N, K))
  
# This code is contributed by Shivam Singh


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to find the cost of
// splitting the arrays into subarray
// with cost less than K
static int make_cuts(int []arr, int n, int K)
{
      
    // Store the possible splits
    int ans = 0;
  
    // Stores the cost of each split
    List poss = new List();
  
    // Stores the count of even numbers
    int ce = 0;
  
    // Stores the count
    // of odd numbers
    int co = 0;
  
    for(int x = 0; x < n - 1; x++)
    {
          
        // Count of odd & even elements
        if (arr[x] % 2 == 0)
            ce++;
        else
            co++;
              
        // Check the required conditions
        // for a valid split
        if (ce == co && co > 0 && ce > 0)
        {
            poss.Add(Math.Abs(arr[x] - 
                              arr[x + 1]));
        }
    }
  
    // Sort the cost of splits
    poss.Sort();
  
    // Find the minimum split costs
    // adding up to sum less than K
    foreach(int x in poss)
    {
        if (K >= x) 
        {
            ans++;
            K -= x;
        }
        else
            break;
    }
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // Given array and K
    int N = 6;
    int K = 4;
  
    int []arr = { 1, 2, 5, 10, 15, 20 };
  
    // Function call
    Console.Write(make_cuts(arr, N, K));
}
}
  
// This code is contributed by Amit Katiyar


输出:
1

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