Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 487. Max Consecutive Ones II
- // Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.
- // ex1
- // Input: nums = [1, 0, 1, 1, 0, 1] - Можем поменять на 1 первый ноль
- // Output: 4
- // ex2
- // Input: nums = [1, 0, 1, 1, 0, 1]
- // Output: 4
- // Решается через скользящее окно
- func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
- var maxLength = 0
- var countZeros = 0
- var l = 0
- for r in 0..<nums.count {
- if nums[r] == 0 {
- countZeros += 1
- }
- while countZeros == 2 {
- // сначала проверяем потом инкрементим, так как l может стоять на 0, мы сдвинем с 0 и не проверим
- if nums[l] == 0 {
- countZeros -= 1
- }
- l += 1
- }
- maxLength = max(maxLength, r-l+1)
- }
- return maxLength
- }
- findMaxConsecutiveOnes([0, 0, 1, 1, 0, 1, 0])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement