|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1004. Max Consecutive Ones III |
| 4 | +# https://leetcode.com/problems/max-consecutive-ones-iii |
| 5 | +# Medium |
| 6 | + |
| 7 | +=begin |
| 8 | +Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 |
| 12 | +Output: 6 |
| 13 | +Explanation: [1,1,1,0,0,1,1,1,1,1,1] |
| 14 | +Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 |
| 18 | +Output: 10 |
| 19 | +Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] |
| 20 | +Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. |
| 21 | +
|
| 22 | +Constraints: |
| 23 | +1 <= nums.length <= 105 |
| 24 | +nums[i] is either 0 or 1. |
| 25 | +0 <= k <= nums.length |
| 26 | +=end |
| 27 | + |
| 28 | +# @param {Integer[]} nums |
| 29 | +# @param {Integer} k |
| 30 | +# @return {Integer} |
| 31 | +def longest_ones(nums, k) |
| 32 | + n = nums.size |
| 33 | + left = right = zeros = max = 0 |
| 34 | + while right < n |
| 35 | + if nums[right] == 0 |
| 36 | + zeros += 1 |
| 37 | + while zeros > k |
| 38 | + if nums[left] == 0 |
| 39 | + zeros -= 1 |
| 40 | + end |
| 41 | + left += 1 |
| 42 | + end |
| 43 | + end |
| 44 | + max = [max, right - left + 1].max |
| 45 | + right += 1 |
| 46 | + end |
| 47 | + |
| 48 | + max |
| 49 | +end |
| 50 | + |
| 51 | +# **************** # |
| 52 | +# TEST # |
| 53 | +# **************** # |
| 54 | + |
| 55 | +require "test/unit" |
| 56 | +class Test_longest_ones < Test::Unit::TestCase |
| 57 | + def test_ |
| 58 | + assert_equal 6, longest_ones([1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], 2) |
| 59 | + assert_equal 10, longest_ones([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], 3) |
| 60 | + end |
| 61 | +end |
0 commit comments