Longest Run of Ones After Flipping k Zeros
Updated
Problem statement
You are given a binary array nums, where every element is 0 or 1, and an integer k.
You may change at most k of the 0s into 1s. Return the length of the longest block of consecutive 1s you can make.
If the array has no 1 and k is 0, there is no block of 1s, so return 0.
Function
longestOnes(nums: int[], k: int) → intExamples
Example 1
nums = [1,0,1,1,0,0,1,1,1]k = 1return = 4Changing the 0 at index 1 gives four 1s at indices 0 to 3. Changing the 0 at index 5 instead gives four 1s at indices 5 to 8. No single change makes a longer block, so the answer is 4.
Example 2
nums = [1,0,1,1,0,0,1,1,1]k = 2return = 7Changing both 0s at indices 4 and 5 joins indices 2 to 8 into one block of 7 ones. The other choices are shorter, so the answer is 7.
Example 3
nums = [0,0,0]k = 0return = 0No changes are allowed and there is no 1 in the array, so the longest block of 1s has length 0.
Constraints
1 <= nums.length <= 10^4nums[i]is0or1.0 <= k <= nums.length
More C3.ai interview questions
- Fewest Turns to Open a Wheel LockPHONE SCREEN · Seen Nov 2024
- Days Until a Warmer DayPHONE SCREEN · ONSITE INTERVIEW · Seen Apr 2022
- Top K Frequent ElementsPHONE SCREEN · Seen Feb 2021
- Item Prices From Material CostsPHONE SCREEN · Seen Dec 2020
- Adjacent-Key Lock PatternsPHONE SCREEN · Seen Feb 2014
- Drop Recent Duplicate MessagesOA · Seen Oct 2026
- Maximum K-Star SumOA · Seen Oct 2026
- Every Result of Grouping an ExpressionONSITE INTERVIEW · Seen Jan 2023
- Fewest Jumps to the Last IndexONSITE INTERVIEW · Seen Jan 2023
- Rotate a Square Grid ClockwiseONSITE INTERVIEW · Seen Jan 2023
Similar questions at other companies
- Minimum Size Subarray SumMicrosoft · OAMicrosoft interview questions
- Random Pick with Weight Using Recorded DrawsGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Maximum Value for Two Delivery RobotsNuro · PHONE SCREENNuro interview questions
- Good Ways to Split an ArraySalesforce · PHONE SCREENSalesforce interview questions
- Two Non-Overlapping Increasing BlocksAdobe · PHONE SCREENAdobe interview questions
- Random Pick with Weight Using Recorded DrawsMeta · PHONE SCREENMeta interview questions
- Count Recorded Events in Time IntervalsSnowflake · PHONE SCREENSnowflake interview questions
- Profit AnalysisVirtu Financial · OAVirtu Financial interview questions
- Choose ContainersIMC Trading · OAIMC Trading interview questions
- Random Pick with Weight Using Recorded DrawsAmazon · ONSITE INTERVIEW