Skip to content

Commit 87528e5

Browse files
committed
1004. Max Consecutive Ones III
1 parent 4acaab2 commit 87528e5

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@
143143
| 989 | Add to Array-Form of Integer | [Ruby](./algorithms/ruby/0989-add-to-array-form-of-integer.rb) | Easy |
144144
| 990 | Satisfiability of Equality Equations | [Ruby](./algorithms/ruby/0990-satisfiability-of-equality-equations.rb) | Medium |
145145
| 994 | Rotting Oranges | [Ruby](./algorithms/ruby/0994-rotting-oranges.rb) | Medium |
146+
| 1004 | Max Consecutive Ones III | [Ruby](./algorithms/ruby/1004-max-consecutive-ones-iii.rb) | Medium |
146147
| 1011 | Capacity To Ship Packages Within D Days | [Ruby](./algorithms/ruby/1011-capacity-to-ship-packages-within-d-days.rb) | Medium |
147148
| 1020 | Number of Enclaves | [Ruby](./algorithms/ruby/1020-number-of-enclaves.rb) | Medium |
148149
| 1046 | Last Stone Weight | [Ruby](./algorithms/ruby/1046-last-stone-weight.rb) | Easy |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)