通过翻转C++中的子数组,最大化0的个数
问题陈述
给定一个二进制数组,找出允许翻转一个子数组的最大0的数目。翻转操作将所有0切换为1,1切换为0
如果arr1= {1, 1, 0, 0, 0, 0, 0}
如果我们把前两个1翻转为0,我们可以得到如下大小为7的子数组−
{0, 0, 0, 0, 0, 0, 0}
算法
1. Consider all subarrays and find a subarray with maximum value of (count of 1s) – (count of 0s) 2. Considers this value be maxDiff. Finally return count of zeros in original array + maxDiff.
范例
#include <bits/stdc++.h> using namespace std; int getMaxSubArray(int *arr, int n){ int maxDiff = 0; int zeroCnt = 0; for (int i = 0; i < n; ++i) { if (arr[i] == 0) { ++zeroCnt; } int cnt0 = 0; int cnt1 = 0; for (int j = i; j < n; ++j) { if (arr[j] == 1) { ++cnt1; } else { ++cnt0; } maxDiff = max(maxDiff, cnt1 - cnt0); } } return zeroCnt + maxDiff; } int main(){ int arr[] = {1, 1, 0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum subarray size = " << getMaxSubArray(arr, n) << endl; return 0; }
输出
当你编译并执行上面的程序时。它生成以下输出−
Maximum subarray size = 7
广告