## Amazon Interview Question

SDE-2s**Country:**United States

```
#include <iostream>
#include <vector>
#include <algorithm>
std::pair<int, int> findMaxConsecutiveOnes(const std::vector<int>& nums, int k) {
int start = 0, end = 0, zeroCount = 0, maxLen = 0, flipIndex = 0;
int leftIndexForMaxLen = 0; // To remember where the maxLen sequence starts.
for (; end < (int)nums.size(); ++end) {
if (nums[end] == 0) {
++zeroCount;
}
// If we have more than k zeros in the window, shrink it from the left
while (zeroCount > k) {
if (nums[start] == 0) {
--zeroCount;
}
++start;
}
// Update maxLen and the starting index of maxLen
if (end - start + 1 > maxLen) {
maxLen = end - start + 1;
leftIndexForMaxLen = start;
}
}
// Find the index to flip. It's the leftmost 0 in the max sequence.
for (int i = leftIndexForMaxLen; i < leftIndexForMaxLen + maxLen; ++i) {
if (nums[i] == 0) {
flipIndex = i;
break; // We just need the first one to maximize the sequence.
}
}
return {flipIndex, maxLen};
}
int main() {
std::vector<int> nums = {1, 1, 1, 0, 1, 0, 0, 1};
int k = 2;
auto result = findMaxConsecutiveOnes(nums, k);
std::cout << "Flip index for maximizing consecutive 1s: " << result.first
<< "\nAfter flipping, maximum consecutive 1s: " << result.second << std::endl;
return 0;
}
```

- ashu July 21, 2020