## Amazon Interview Question for SDE-2s

Country: United States

Comment hidden because of low score. Click to expand.
1
of 1 vote

``````int zc=0,l=0,max=0;
for(int i=0;i<nums.length;i++){

if(nums[i]==0)
zc++;
while(zc>k){
if(nums[l++]==0)
zc--;
}
max=Math.max(max,i-l+1);
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````int zi=-1,l=-1,max=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==0) {
if(!l<0)
max=Math.max(i-l);
l=zi+1;
zi=i;
}
}``````

``````int zc=0,l=0,max=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==0) {
zc++;
}
while(zc>k){
if(nums[l++]==0)
zc--;
}
max=Math.max(max,i-l+1);
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````int zc=0,l=0,max=0;
for(int i=0;i<nums.length;i++){

if(nums[i]==0)
zc++;
while(zc>k){
if(nums[l++]==0)
zc--;
}
max=Math.max(max,i-l+1);
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

iterate a given array while keeping track of max consecutive 1s so far and counting running consecutive 1s. Compare max so far and running num.

iterate the input array by counting the number of zeros.

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````#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;
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.