📌  相关文章
📜  删除一对连续的Array元素后,最大化1的子数组的长度

📅  最后修改于: 2021-05-17 21:58:28             🧑  作者: Mango

给定一个由N个元素组成的二进制数组arr [] ,任务是在删除一对连续的数组元素后,找到仅1个子数组的最大可能长度。如果不存在这样的子数组,则打印-1

例子:

天真的方法:
解决问题的最简单方法是从数组中生成所有可能的连续元素对,并为每个对计算1的子数组的最大可能长度。最后打印获得的此类子数组的最大可能长度。

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

高效方法:
请按照以下步骤解决问题:

  • 初始化辅助2D向量V。
  • 跟踪仅由1组成的所有连续子数组。
  • 存储子数组的length开始索引结束索引
  • 现在,计算1的任意两个子数组之间的0数。
  • 基于获得的这些0计数,更新可能的最大子数组长度:
    • 如果两个子阵列之间恰好存在两个0 ,则通过与两个子阵列的组合长度进行比较来更新最大可能长度
    • 如果两个子阵列之间恰好存在一个0,则通过与两个子阵列的组合长度进行比较来更新最大可能长度– 1。
  • 最后,打印获得的最大可能长度

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the maximum
// subarray length of ones
int maxLen(int A[], int N)
{
    // Stores the length, starting
    // index and ending index of the
    // subarrays
    vector > v;
 
    for (int i = 0; i < N; i++) {
 
        if (A[i] == 1) {
 
            // S : starting index
            // of the sub-array
            int s = i, len;
 
            // Traverse only continous 1s
            while (A[i] == 1 && i < N) {
                i++;
            }
 
            // Calculate length of the
            // sub-array
            len = i - s;
 
            // v[i][0] : Length of subarray
            // v[i][1] : Starting Index of subarray
            // v[i][2] : Ending Index of subarray
            v.push_back({ len, s, i - 1 });
        }
    }
 
    // If no such sub-array exists
    if (v.size() == 0) {
        return -1;
    }
 
    int ans = 0;
 
    // Traversing through the subarrays
    for (int i = 0; i < v.size() - 1; i++) {
 
        // Update maximum length
        ans = max(ans, v[i][0]);
 
        // v[i+1][1] : Starting index of
        // the next Sub-Array
 
        // v[i][2] : Ending Index of the
        // current Sub-Array
 
        // v[i+1][1] - v[i][2] - 1 : Count of
        // zeros between the two sub-arrays
        if (v[i + 1][1] - v[i][2] - 1 == 2) {
 
            // Update length of both subarrays
            // to the maximum
            ans = max(ans, v[i][0] + v[i + 1][0]);
        }
        if (v[i + 1][1] - v[i][2] - 1 == 1) {
 
            // Update length of both subarrays - 1
            // to the maximum
            ans = max(ans, v[i][0] + v[i + 1][0] - 1);
        }
    }
 
    // Check if the last subarray has
    // the maximum length
    ans = max(v[v.size() - 1][0], ans);
 
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 0, 1, 0, 0, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << maxLen(arr, N) << endl;
    return 0;
}


Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find the maximum
    // subarray length of ones
    static int maxLen(int A[], int N)
    {
 
        // Stores the length, starting
        // index and ending index of the
        // subarrays
        List > v = new ArrayList<>();
 
        for (int i = 0; i < N; i++) {
            if (A[i] == 1) {
 
                // S : starting index
                // of the sub-array
                int s = i, len;
 
                // Traverse only continous 1s
                while (i < N && A[i] == 1) {
                    i++;
                }
 
                // Calculate length of the
                // sub-array
                len = i - s;
 
                // v[i][0] : Length of subarray
                // v[i][1] : Starting Index of subarray
                // v[i][2] : Ending Index of subarray
                v.add(Arrays.asList(len, s, i - 1));
            }
        }
 
        // If no such sub-array exists
        if (v.size() == 0) {
            return -1;
        }
 
        int ans = 0;
 
        // Traversing through the subarrays
        for (int i = 0; i < v.size() - 1; i++) {
 
            // Update maximum length
            ans = Math.max(ans, v.get(i).get(0));
 
            // v[i+1][1] : Starting index of
            // the next Sub-Array
 
            // v[i][2] : Ending Index of the
            // current Sub-Array
 
            // v[i+1][1] - v[i][2] - 1 : Count of
            // zeros between the two sub-arrays
            if (v.get(i + 1).get(1) - v.get(i).get(2) - 1
                == 2) {
 
                // Update length of both subarrays
                // to the maximum
                ans = Math.max(ans,
                               v.get(i).get(0)
                                   + v.get(i + 1).get(0));
            }
            if (v.get(i + 1).get(1) - v.get(i).get(2) - 1
                == 1) {
 
                // Update length of both subarrays - 1
                // to the maximum
                ans = Math.max(
                    ans, v.get(i).get(0)
                             + v.get(i + 1).get(0) - 1);
            }
        }
 
        // Check if the last subarray has
        // the maximum length
        ans = Math.max(v.get(v.size() - 1).get(0), ans);
 
        return ans;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int arr[] = { 1, 0, 1, 0, 0, 1 };
        int N = arr.length;
 
        System.out.println(maxLen(arr, N));
    }
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach
 
# Function to find the maximum
# subarray length of ones
 
 
def maxLen(A, N):
 
    # Stores the length, starting
    # index and ending index of the
    # subarrays
    v = []
 
    i = 0
    while i < N:
        if (A[i] == 1):
 
            # S : starting index
            # of the sub-array
            s = i
 
            # Traverse only continous 1s
            while (i < N and A[i] == 1):
                i += 1
 
            # Calculate length of the
            # sub-array
            le = i - s
 
            # v[i][0] : Length of subarray
            # v[i][1] : Starting Index of subarray
            # v[i][2] : Ending Index of subarray
            v.append([le, s, i - 1])
 
        i += 1
 
    # If no such sub-array exists
    if (len(v) == 0):
        return -1
 
    ans = 0
 
    # Traversing through the subarrays
    for i in range(len(v) - 1):
 
        # Update maximum length
        ans = max(ans, v[i][0])
 
        # v[i+1][1] : Starting index of
        # the next Sub-Array
 
        # v[i][2] : Ending Index of the
        # current Sub-Array
 
        # v[i+1][1] - v[i][2] - 1 : Count of
        # zeros between the two sub-arrays
        if (v[i + 1][1] - v[i][2] - 1 == 2):
 
            # Update length of both subarrays
            # to the maximum
            ans = max(ans, v[i][0] + v[i + 1][0])
 
        if (v[i + 1][1] - v[i][2] - 1 == 1):
 
            # Update length of both subarrays - 1
            # to the maximum
            ans = max(ans, v[i][0] + v[i + 1][0] - 1)
 
    # Check if the last subarray has
    # the maximum length
    ans = max(v[len(v) - 1][0], ans)
 
    return ans
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 0, 1, 0, 0, 1]
    N = len(arr)
 
    print(maxLen(arr, N))
 
# This code is contributed by chitranayal


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to find the maximum
    // subarray length of ones
    static int maxLen(int []A, int N)
    {
 
        // Stores the length, starting
        // index and ending index of the
        // subarrays
        List> v = new List>();
 
        for (int i = 0; i < N; i++)
        {
            if (A[i] == 1)
            {
 
                // S : starting index
                // of the sub-array
                int s = i, len;
 
                // Traverse only continous 1s
                while (i < N && A[i] == 1)
                {
                    i++;
                }
 
                // Calculate length of the
                // sub-array
                len = i - s;
 
                // v[i,0] : Length of subarray
                // v[i,1] : Starting Index of subarray
                // v[i,2] : Ending Index of subarray
                List l = new List{len, s, i - 1};
                v.Add(l);
            }
        }
 
        // If no such sub-array exists
        if (v.Count == 0)
        {
            return -1;
        }
 
        int ans = 0;
 
        // Traversing through the subarrays
        for (int i = 0; i < v.Count - 1; i++)
        {
 
            // Update maximum length
            ans = Math.Max(ans, v[i][0]);
 
            // v[i+1,1] : Starting index of
            // the next Sub-Array
 
            // v[i,2] : Ending Index of the
            // current Sub-Array
 
            // v[i+1,1] - v[i,2] - 1 : Count of
            // zeros between the two sub-arrays
            if (v[i + 1][1] - v[i][2] - 1
                == 2) {
 
                // Update length of both subarrays
                // to the maximum
                ans = Math.Max(ans,
                               v[i][0]
                                   + v[i + 1][0]);
            }
            if (v[i + 1][1] - v[i][2] - 1
                == 1)
            {
 
                // Update length of both subarrays - 1
                // to the maximum
                ans = Math.Max(
                    ans, v[i][0]
                             + v[i + 1][0] - 1);
            }
        }
 
        // Check if the last subarray has
        // the maximum length
        ans = Math.Max(v[v.Count - 1][0], ans);
 
        return ans;
    }
 
    // Driver Code
    public static void Main(String []args)
    {
        int []arr = { 1, 0, 1, 0, 0, 1 };
        int N = arr.Length;
 
        Console.WriteLine(maxLen(arr, N));
    }
}
 
// This code is contributed by Princi Singh


C++
// C++ program to find the maximum count of 1s
#include 
using namespace std;
 
void maxLengthOf1s(vector arr, int n)
{
    vector prefix(n, 0);
    for (int i = 2; i < n; i++)
    {
        // If arr[i-2]==1 then we increment the
        // count of occurences of 1's
        if (arr[i - 2]
            == 1)
            prefix[i] = prefix[i - 1] + 1;
       
        // else we initialise the count with 0
        else
            prefix[i] = 0;
    }
    vector suffix(n, 0);
    for (int i = n - 3; i >= 0; i--)
    {
        // If arr[i+2]==1 then we increment the
        // count of occurences of 1's
        if (arr[i + 2] == 1)
            suffix[i] = suffix[i + 1] + 1;
       
        // else we initialise the count with 0
        else
            suffix[i] = 0;
    }
    int ans = 0;
    for (int i = 0; i < n - 1; i++)
    {
        // We get the maximum count by
        // skipping the current and the
        // next element.
        ans = max(ans, prefix[i + 1] + suffix[i]);
    }
    cout << ans << "\n";
}
 
// Driver Code
int main()
{
    int n = 6;
    vector arr = { 1, 1, 1, 0, 1, 1 };
    maxLengthOf1s(arr, n);
    return 0;
}


Java
// Java program to find the maximum count of 1s
class GFG{
     
public static void maxLengthOf1s(int arr[], int n)
{
    int prefix[] = new int[n];
     
    for(int i = 2; i < n; i++)
    {
         
        // If arr[i-2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i - 2] == 1)
            prefix[i] = prefix[i - 1] + 1;
        
        // Else we initialise the count with 0
        else
            prefix[i] = 0;
    }
    int suffix[] = new int[n];
    for(int i = n - 3; i >= 0; i--)
    {
         
        // If arr[i+2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i + 2] == 1)
            suffix[i] = suffix[i + 1] + 1;
        
        // Else we initialise the count with 0
        else
            suffix[i] = 0;
    }
    int ans = 0;
    for(int i = 0; i < n - 1; i++)
    {
         
        // We get the maximum count by
        // skipping the current and the
        // next element.
        ans = Math.max(ans, prefix[i + 1] +
                            suffix[i]);
    }
    System.out.println(ans);
}
 
// Driver code
public static void main(String[] args)
{
    int n = 6;
    int arr[] = { 1, 1, 1, 0, 1, 1 };
     
    maxLengthOf1s(arr, n);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python program to find the maximum count of 1s
def maxLengthOf1s(arr, n):
    prefix = [0 for i in range(n)]
    for i in range(2, n):
 
        # If arr[i-2]==1 then we increment
        # the count of occurences of 1's
        if(arr[i - 2] == 1):
            prefix[i] = prefix[i - 1] + 1
         
        # Else we initialise the count with 0
        else:
            prefix[i] = 0
    suffix = [0 for i in range(n)]
    for i in range(n - 3, -1, -1):
         
        # If arr[i+2]==1 then we increment
        # the count of occurences of 1's
        if(arr[i + 2] == 1):
            suffix[i] = suffix[i + 1] + 1
             
        # Else we initialise the count with 0
        else:
            suffix[i] = 0
    ans = 0
    for i in range(n - 1):
       
        # We get the maximum count by
        # skipping the current and the
        # next element.
        ans = max(ans, prefix[i + 1] + suffix[i])
    print(ans)
 
# Driver code
n = 6
arr = [1, 1, 1, 0, 1, 1]
maxLengthOf1s(arr, n)
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program to find the maximum count of 1s
using System;
 
class GFG{
     
static void maxLengthOf1s(int[] arr, int n)
{
    int[] prefix = new int[n];
     
    for(int i = 2; i < n; i++)
    {
         
        // If arr[i-2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i - 2] == 1)
            prefix[i] = prefix[i - 1] + 1;
         
        // Else we initialise the count with 0
        else
            prefix[i] = 0;
    }
    int[] suffix = new int[n];
    for(int i = n - 3; i >= 0; i--)
    {
         
        // If arr[i+2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i + 2] == 1)
            suffix[i] = suffix[i + 1] + 1;
         
        // Else we initialise the count with 0
        else
            suffix[i] = 0;
    }
    int ans = 0;
    for(int i = 0; i < n - 1; i++)
    {
         
        // We get the maximum count by
        // skipping the current and the
        // next element.
        ans = Math.Max(ans, prefix[i + 1] + suffix[i]);
    }
    Console.WriteLine(ans);
}
 
// Driver code
static void Main()
{
    int n = 6;
    int[] arr = { 1, 1, 1, 0, 1, 1 };
      
    maxLengthOf1s(arr, n);
}
}
 
// This code is contributed by divyesh072019


Javascript


输出
2

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

方法2:

前缀和后缀数组

计数出现0到1之间的1的数量。如果找到0,那么如果我们跳过连续的2个元素,则需要找到1的最大长度。我们可以使用Prefix和Suffix数组的概念来解决此问题。

从数组的开头查找连续的1s的长度,并将计数存储在前缀数组中。从数组结尾处查找连续的1s的长度,并将计数存储在结尾数组中。

我们遍历两个数组并找到最大值。的1秒。

算法:

  1. 创建长度为n的两个数组前缀和后缀。
  2. 初始化前缀[0] = 0,前缀[1] = 0,后缀[n-1] = 0,后缀[n-2] = 0。这告诉我们在前2个元素之前和后2个元素之后没有1。
  3. 从2到n-1运行循环:
    • 如果arr [i-2] == 1
      • 前缀[i] =前缀[i-1] +1
    • 否则,如果arr [i-2] == 0:
      • 前缀[i] = 0
  4. 从n-3到0运行循环:
    • 如果arr [i + 2] == 1
      • 后缀[i] =后缀[i + 1] +1
    • 否则,如果arr [i-2] == 0:
      • 后缀[i] = 0
  5. 初始化答案= INT_MIN
  6. 对于i = 0到n-2://通过跳过当前元素和下一个元素来计算1的数量。
  7. answer = max(answer,prefix [i + 1] +后缀[i]
  8. 打印答案

执行:

C++

// C++ program to find the maximum count of 1s
#include 
using namespace std;
 
void maxLengthOf1s(vector arr, int n)
{
    vector prefix(n, 0);
    for (int i = 2; i < n; i++)
    {
        // If arr[i-2]==1 then we increment the
        // count of occurences of 1's
        if (arr[i - 2]
            == 1)
            prefix[i] = prefix[i - 1] + 1;
       
        // else we initialise the count with 0
        else
            prefix[i] = 0;
    }
    vector suffix(n, 0);
    for (int i = n - 3; i >= 0; i--)
    {
        // If arr[i+2]==1 then we increment the
        // count of occurences of 1's
        if (arr[i + 2] == 1)
            suffix[i] = suffix[i + 1] + 1;
       
        // else we initialise the count with 0
        else
            suffix[i] = 0;
    }
    int ans = 0;
    for (int i = 0; i < n - 1; i++)
    {
        // We get the maximum count by
        // skipping the current and the
        // next element.
        ans = max(ans, prefix[i + 1] + suffix[i]);
    }
    cout << ans << "\n";
}
 
// Driver Code
int main()
{
    int n = 6;
    vector arr = { 1, 1, 1, 0, 1, 1 };
    maxLengthOf1s(arr, n);
    return 0;
}

Java

// Java program to find the maximum count of 1s
class GFG{
     
public static void maxLengthOf1s(int arr[], int n)
{
    int prefix[] = new int[n];
     
    for(int i = 2; i < n; i++)
    {
         
        // If arr[i-2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i - 2] == 1)
            prefix[i] = prefix[i - 1] + 1;
        
        // Else we initialise the count with 0
        else
            prefix[i] = 0;
    }
    int suffix[] = new int[n];
    for(int i = n - 3; i >= 0; i--)
    {
         
        // If arr[i+2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i + 2] == 1)
            suffix[i] = suffix[i + 1] + 1;
        
        // Else we initialise the count with 0
        else
            suffix[i] = 0;
    }
    int ans = 0;
    for(int i = 0; i < n - 1; i++)
    {
         
        // We get the maximum count by
        // skipping the current and the
        // next element.
        ans = Math.max(ans, prefix[i + 1] +
                            suffix[i]);
    }
    System.out.println(ans);
}
 
// Driver code
public static void main(String[] args)
{
    int n = 6;
    int arr[] = { 1, 1, 1, 0, 1, 1 };
     
    maxLengthOf1s(arr, n);
}
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python program to find the maximum count of 1s
def maxLengthOf1s(arr, n):
    prefix = [0 for i in range(n)]
    for i in range(2, n):
 
        # If arr[i-2]==1 then we increment
        # the count of occurences of 1's
        if(arr[i - 2] == 1):
            prefix[i] = prefix[i - 1] + 1
         
        # Else we initialise the count with 0
        else:
            prefix[i] = 0
    suffix = [0 for i in range(n)]
    for i in range(n - 3, -1, -1):
         
        # If arr[i+2]==1 then we increment
        # the count of occurences of 1's
        if(arr[i + 2] == 1):
            suffix[i] = suffix[i + 1] + 1
             
        # Else we initialise the count with 0
        else:
            suffix[i] = 0
    ans = 0
    for i in range(n - 1):
       
        # We get the maximum count by
        # skipping the current and the
        # next element.
        ans = max(ans, prefix[i + 1] + suffix[i])
    print(ans)
 
# Driver code
n = 6
arr = [1, 1, 1, 0, 1, 1]
maxLengthOf1s(arr, n)
 
# This code is contributed by avanitrachhadiya2155

C#

// C# program to find the maximum count of 1s
using System;
 
class GFG{
     
static void maxLengthOf1s(int[] arr, int n)
{
    int[] prefix = new int[n];
     
    for(int i = 2; i < n; i++)
    {
         
        // If arr[i-2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i - 2] == 1)
            prefix[i] = prefix[i - 1] + 1;
         
        // Else we initialise the count with 0
        else
            prefix[i] = 0;
    }
    int[] suffix = new int[n];
    for(int i = n - 3; i >= 0; i--)
    {
         
        // If arr[i+2]==1 then we increment
        // the count of occurences of 1's
        if (arr[i + 2] == 1)
            suffix[i] = suffix[i + 1] + 1;
         
        // Else we initialise the count with 0
        else
            suffix[i] = 0;
    }
    int ans = 0;
    for(int i = 0; i < n - 1; i++)
    {
         
        // We get the maximum count by
        // skipping the current and the
        // next element.
        ans = Math.Max(ans, prefix[i + 1] + suffix[i]);
    }
    Console.WriteLine(ans);
}
 
// Driver code
static void Main()
{
    int n = 6;
    int[] arr = { 1, 1, 1, 0, 1, 1 };
      
    maxLengthOf1s(arr, n);
}
}
 
// This code is contributed by divyesh072019

Java脚本


输出
4

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