透過翻轉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
廣告