📌  相关文章
📜  通过翻转子数组来最大化 0 的数量

📅  最后修改于: 2022-05-13 01:57:48.748000             🧑  作者: Mango

通过翻转子数组来最大化 0 的数量

给定一个二进制数组,找出数组中允许翻转子数组的最大零个数。翻转操作将所有 0 切换为 1,将 1 切换为 0。
例子:

Input :  arr[] = {0, 1, 0, 0, 1, 1, 0}
Output : 6
We can get 6 zeros by flipping the subarray {4, 5}

Input :  arr[] = {0, 0, 0, 1, 0, 1}
Output : 5

方法 1(简单:O(n 2 ))
一个简单的解决方案是考虑所有子数组并找到最大值为(count of 1s) – (count of 0s) 的子数组。让这个值为 max_diff。最后,返回原始数组中的零计数加上 max_diff。

C++
// C++ program to maximize number of zeroes in a
// binary array by at most one flip operation
#include
using namespace std;
 
// A Kadane's algorithm based solution to find maximum
// number of 0s by flipping a subarray.
int findMaxZeroCount(bool arr[], int n)
{
    // Initialize max_diff = maximum of (Count of 0s -
    // count of 1s) for all subarrays.
    int max_diff = 0;
 
    // Initialize count of 0s in original array
    int orig_zero_count = 0;
 
    // Consider all Subarrays by using two nested two
    // loops
    for (int i=0; i


Java
// Java code for Maximize number of 0s by flipping
// a subarray
class GFG {
      
    // A Kadane's algorithm based solution to find maximum
    // number of 0s by flipping a subarray.
    public static int findMaxZeroCount(int arr[], int n)
    {
        // Initialize max_diff = maximum of (Count of 0s -
        // count of 1s) for all subarrays.
        int max_diff = 0;
      
        // Initialize count of 0s in original array
        int orig_zero_count = 0;
      
        // Consider all Subarrays by using two nested two
        // loops
        for (int i=0; i


Python3
# Python3 program to maximize number of
# zeroes in a binary array by at most
# one flip operation
 
# A Kadane's algorithm based solution
# to find maximum number of 0s by
# flipping a subarray.
def findMaxZeroCount(arr, n):
     
    # Initialize max_diff = maximum
    # of (Count of 0s - count of 1s)
    # for all subarrays.
    max_diff = 0
     
    # Initialize count of 0s in
    # original array
    orig_zero_count = 0
     
    # Consider all Subarrays by using
    # two nested two loops
    for i in range(n):
         
        # Increment count of zeros
        if arr[i] == 0:
            orig_zero_count += 1
         
        # Initialize counts of 0s and 1s
        count1, count0 = 0, 0
         
        # Consider all subarrays starting
        # from arr[i] and find the
        # difference between 1s and 0s.
        # Update max_diff if required
        for j in range(i, n):
            if arr[j] == 1:
                count1 += 1
            else:
                count0 += 1
                 
            max_diff = max(max_diff, count1 -
                                     count0)
     
    # Final result would be count of 0s
    # in original array plus max_diff.
    return orig_zero_count + max_diff
 
# Driver code
arr = [ 0, 1, 0, 0, 1, 1, 0 ]
n = len(arr)
 
print(findMaxZeroCount(arr, n))
 
# This code is contributed by stutipathak31jan


C#
// C# code for Maximize number of 0s by
// flipping a subarray
using System;
 
class GFG{
     
// A Kadane's algorithm based solution
// to find maximum number of 0s by
// flipping a subarray.
public static int findMaxZeroCount(int []arr,
                                   int n)
{
     
    // Initialize max_diff = maximum of
    // (Count of 0s - count of 1s) for
    // all subarrays.
    int max_diff = 0;
 
    // Initialize count of 0s in
    // original array
    int orig_zero_count = 0;
 
    // Consider all Subarrays by
    // using two nested two loops
    for(int i = 0; i < n; i++)
    {
         
        // Increment count of zeros
        if (arr[i] == 0)
            orig_zero_count++;
 
        // Initialize counts of 0s and 1s
        int count1 = 0, count0 = 0;
 
        // Consider all subarrays starting
        // from arr[i] and find the difference
        // between 1s and 0s.
        // Update max_diff if required
        for(int j = i; j < n; j ++)
        {
            if(arr[j] == 1)
                count1++;
                 
            else count0++;
            max_diff = Math.Max(max_diff,
                                count1 - count0);
        }
    }
 
    // Final result would be count of 0s in original
    // array plus max_diff.
    return orig_zero_count + max_diff;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 0, 1, 0, 0, 1, 1, 0 };
     
    Console.WriteLine(
        findMaxZeroCount(arr, arr.Length));
}
}
 
// This code is contributed by amal kumar choubey


Javascript


C++
// C++ program to maximize number of zeroes in a
// binary array by at most one flip operation
#include
using namespace std;
 
// A Kadane's algorithm based solution to find maximum
// number of 0s by flipping a subarray.
int findMaxZeroCount(bool arr[], int n)
{
    // Initialize count of zeros and maximum difference
    // between count of 1s and 0s in a subarray
    int orig_zero_count = 0;
 
    // Initiale overall max diff for any subarray
    int max_diff = 0;
 
    // Initialize current diff
    int curr_max = 0;
 
    for (int i=0; i


Java
// Java code for Maximize number of 0s by
// flipping a subarray
class GFG {
      
    // A Kadane's algorithm based solution to find maximum
    // number of 0s by flipping a subarray.
    public static int findMaxZeroCount(int arr[], int n)
    {
        // Initialize count of zeros and maximum difference
        // between count of 1s and 0s in a subarray
        int orig_zero_count = 0;
      
        // Initiale overall max diff for any subarray
        int max_diff = 0;
      
        // Initialize current diff
        int curr_max = 0;
      
        for (int i = 0; i < n; i ++)
        {
            // Count of zeros in original array (Not related
            // to Kadane's algorithm)
            if (arr[i] == 0)
               orig_zero_count ++;
      
            // Value to be considered for finding maximum sum
            int val = (arr[i] == 1)? 1 : -1;
      
            // Update current max and max_diff
            curr_max = Math.max(val, curr_max + val);
            max_diff = Math.max(max_diff, curr_max);
        }
        max_diff = Math.max(0, max_diff);
      
        return orig_zero_count + max_diff;
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = {0, 1, 0, 0, 1, 1, 0};
         
        System.out.println(findMaxZeroCount(arr, arr.length));
    }
  }
// This code is contributed by Arnav Kr. Mandal.


Python3
# Python3 program to maximize number
# of zeroes in a binary array by at
# most one flip operation
 
# A Kadane's algorithm based solution
# to find maximum number of 0s by
# flipping a subarray.
def findMaxZeroCount(arr, n):
     
    # Initialize count of zeros and
    # maximum difference between count
    # of 1s and 0s in a subarray
    orig_zero_count = 0
     
    # Initialize overall max diff
    # for any subarray
    max_diff = 0
     
    # Initialize current diff
    curr_max = 0
     
    for i in range(n):
         
        # Count of zeros in original
        # array (Not related to
        # Kadane's algorithm)
        if arr[i] == 0:
            orig_zero_count += 1
         
        # Value to be considered for
        # finding maximum sum
        val = 1 if arr[i] == 1 else -1
         
        # Update current max and max_diff
        curr_max = max(val, curr_max + val)
        max_diff = max(max_diff, curr_max)
         
    max_diff = max(0, max_diff)
     
    return orig_zero_count + max_diff
 
# Driver code
arr = [ 0, 1, 0, 0, 1, 1, 0 ]
n = len(arr)
 
print(findMaxZeroCount(arr, n))
 
# This code is contributed by stutipathak31jan


C#
// C# code for Maximize number of 0s by
// flipping a subarray
using System;
class GFG{
      
  // A Kadane's algorithm based solution to find maximum
  // number of 0s by flipping a subarray.
  public static int findMaxZeroCount(int []arr, int n)
  {
    // Initialize count of zeros and maximum difference
    // between count of 1s and 0s in a subarray
    int orig_zero_count = 0;
 
    // Initiale overall max diff for any subarray
    int max_diff = 0;
 
    // Initialize current diff
    int curr_max = 0;
 
    for (int i = 0; i < n; i ++)
    {
      // Count of zeros in original array (Not related
      // to Kadane's algorithm)
      if (arr[i] == 0)
        orig_zero_count ++;
 
      // Value to be considered for finding maximum sum
      int val = (arr[i] == 1)? 1 : -1;
 
      // Update current max and max_diff
      curr_max = Math.Max(val, curr_max + val);
      max_diff = Math.Max(max_diff, curr_max);
    }
    max_diff = Math.Max(0, max_diff);
 
    return orig_zero_count + max_diff;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []arr = {0, 1, 0, 0, 1, 1, 0};
 
    Console.WriteLine(findMaxZeroCount(arr, arr.Length));
  }
}
 
// This code is contributed by Rohit_ranjan


Javascript


输出:

6

方法2(效率:O(n))
这个问题可以简化为最大子数组和问题。这个想法是将每个0视为-1,将每个1视为1,在这个修改后的数组中找到最大子数组和的总和。这个总和是我们所需的 max_diff(0 的计数 - 任何子数组中 1 的计数)。最后,我们返回原始数组中的 max_diff 加上零个数。

C++

// C++ program to maximize number of zeroes in a
// binary array by at most one flip operation
#include
using namespace std;
 
// A Kadane's algorithm based solution to find maximum
// number of 0s by flipping a subarray.
int findMaxZeroCount(bool arr[], int n)
{
    // Initialize count of zeros and maximum difference
    // between count of 1s and 0s in a subarray
    int orig_zero_count = 0;
 
    // Initiale overall max diff for any subarray
    int max_diff = 0;
 
    // Initialize current diff
    int curr_max = 0;
 
    for (int i=0; i

Java

// Java code for Maximize number of 0s by
// flipping a subarray
class GFG {
      
    // A Kadane's algorithm based solution to find maximum
    // number of 0s by flipping a subarray.
    public static int findMaxZeroCount(int arr[], int n)
    {
        // Initialize count of zeros and maximum difference
        // between count of 1s and 0s in a subarray
        int orig_zero_count = 0;
      
        // Initiale overall max diff for any subarray
        int max_diff = 0;
      
        // Initialize current diff
        int curr_max = 0;
      
        for (int i = 0; i < n; i ++)
        {
            // Count of zeros in original array (Not related
            // to Kadane's algorithm)
            if (arr[i] == 0)
               orig_zero_count ++;
      
            // Value to be considered for finding maximum sum
            int val = (arr[i] == 1)? 1 : -1;
      
            // Update current max and max_diff
            curr_max = Math.max(val, curr_max + val);
            max_diff = Math.max(max_diff, curr_max);
        }
        max_diff = Math.max(0, max_diff);
      
        return orig_zero_count + max_diff;
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = {0, 1, 0, 0, 1, 1, 0};
         
        System.out.println(findMaxZeroCount(arr, arr.length));
    }
  }
// This code is contributed by Arnav Kr. Mandal.

Python3

# Python3 program to maximize number
# of zeroes in a binary array by at
# most one flip operation
 
# A Kadane's algorithm based solution
# to find maximum number of 0s by
# flipping a subarray.
def findMaxZeroCount(arr, n):
     
    # Initialize count of zeros and
    # maximum difference between count
    # of 1s and 0s in a subarray
    orig_zero_count = 0
     
    # Initialize overall max diff
    # for any subarray
    max_diff = 0
     
    # Initialize current diff
    curr_max = 0
     
    for i in range(n):
         
        # Count of zeros in original
        # array (Not related to
        # Kadane's algorithm)
        if arr[i] == 0:
            orig_zero_count += 1
         
        # Value to be considered for
        # finding maximum sum
        val = 1 if arr[i] == 1 else -1
         
        # Update current max and max_diff
        curr_max = max(val, curr_max + val)
        max_diff = max(max_diff, curr_max)
         
    max_diff = max(0, max_diff)
     
    return orig_zero_count + max_diff
 
# Driver code
arr = [ 0, 1, 0, 0, 1, 1, 0 ]
n = len(arr)
 
print(findMaxZeroCount(arr, n))
 
# This code is contributed by stutipathak31jan

C#

// C# code for Maximize number of 0s by
// flipping a subarray
using System;
class GFG{
      
  // A Kadane's algorithm based solution to find maximum
  // number of 0s by flipping a subarray.
  public static int findMaxZeroCount(int []arr, int n)
  {
    // Initialize count of zeros and maximum difference
    // between count of 1s and 0s in a subarray
    int orig_zero_count = 0;
 
    // Initiale overall max diff for any subarray
    int max_diff = 0;
 
    // Initialize current diff
    int curr_max = 0;
 
    for (int i = 0; i < n; i ++)
    {
      // Count of zeros in original array (Not related
      // to Kadane's algorithm)
      if (arr[i] == 0)
        orig_zero_count ++;
 
      // Value to be considered for finding maximum sum
      int val = (arr[i] == 1)? 1 : -1;
 
      // Update current max and max_diff
      curr_max = Math.Max(val, curr_max + val);
      max_diff = Math.Max(max_diff, curr_max);
    }
    max_diff = Math.Max(0, max_diff);
 
    return orig_zero_count + max_diff;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []arr = {0, 1, 0, 0, 1, 1, 0};
 
    Console.WriteLine(findMaxZeroCount(arr, arr.Length));
  }
}
 
// This code is contributed by Rohit_ranjan

Javascript


输出:

6