Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Maximize Number of 1's

Medium Acceptance 50.00% Points 30.00

Given a binary array arr[] containing only 0s and 1s and an integer k, you are allowed to flip at most k 0s to 1s. Find the maximum number of consecutive 1's that can be obtained in the array after performing the operation at most k times.

Examples
Example 1

Example 1

Input: arr[] = [1, 0, 1], k = 1

Output: 3

Explanation: By flipping the zero at index 1, we get the longest subarray from index 0 to 2 containing all 1’s.

Example 2

Example 2

Input: arr[] = [1, 0, 0, 1, 0, 1, 0, 1], k = 2

Output: 5

Explanation: By flipping the zeroes at indices 4 and 6, we get the longest subarray from index 3 to 7 containing all 1’s.

Example 3

Example 3

Input: arr[] = [1, 1], k = 2

Output: 2

Explanation: Since the array is already having the max consecutive 1's, hence we dont need to perform any operation. Hence the answer is 2.

Hints
Hint 1
NA
Constraints
  • 1 = arr.size() = 10^5
  • 0 = k = arr.size()
  • 0 = arr[i] = 1
Companies
Amazon Microsoft
Topics
Array Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions