- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path1004-max-consecutive-ones-iii.rb
61 lines (52 loc) · 1.43 KB
/
1004-max-consecutive-ones-iii.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# frozen_string_literal: true
# 1004. Max Consecutive Ones III
# https://leetcode.com/problems/max-consecutive-ones-iii
# Medium
=begin
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.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Constraints:
1 <= nums.length <= 105
nums[i] is either 0 or 1.
0 <= k <= nums.length
=end
# @param {Integer[]} nums
# @param {Integer} k
# @return {Integer}
deflongest_ones(nums,k)
n=nums.size
left=right=zeros=max=0
whileright < n
ifnums[right] == 0
zeros += 1
whilezeros > k
ifnums[left] == 0
zeros -= 1
end
left += 1
end
end
max=[max,right - left + 1].max
right += 1
end
max
end
# **************** #
# TEST #
# **************** #
require"test/unit"
classTest_longest_ones < Test::Unit::TestCase
deftest_
assert_equal6,longest_ones([1,1,1,0,0,0,1,1,1,1,0],2)
assert_equal10,longest_ones([0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1],3)
end
end