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

📅  最后修改于: 2021-09-03 13:44:33             🧑  作者: Mango

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

例子:

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

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

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

  • 初始化一个辅助二维向量V
  • 跟踪所有仅由1组成的连续子数组。
  • 存储子数组的长度起始索引结束索引
  • 现在,计算任意两个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


Javascript


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)

方法二:

前缀和后缀数组

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

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

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

算法:

  1. 创建两个长度为 n 的数组前缀和后缀。
  2. 初始化 prefix[0]=0,prefix[1]=0 和 suffix[n-1]=0,suffix[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. for i=0 to n-2: //通过跳过当前和下一个元素来计算 1 的数量。
  7. answer=max(answer,prefix[i+1]+suffix[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

蟒蛇3

# 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


输出
4

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live