|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1493. Longest Subarray of 1's After Deleting One Element |
| 4 | +# https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element |
| 5 | +# Medium |
| 6 | + |
| 7 | +=begin |
| 8 | +Given a binary array nums, you should delete one element from it. |
| 9 | +
|
| 10 | +Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. |
| 11 | +
|
| 12 | +Example 1: |
| 13 | +Input: nums = [1,1,0,1] |
| 14 | +Output: 3 |
| 15 | +Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. |
| 16 | +
|
| 17 | +Example 2: |
| 18 | +Input: nums = [0,1,1,1,0,1,1,0,1] |
| 19 | +Output: 5 |
| 20 | +Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. |
| 21 | +
|
| 22 | +Example 3: |
| 23 | +Input: nums = [1,1,1] |
| 24 | +Output: 2 |
| 25 | +Explanation: You must delete one element. |
| 26 | +
|
| 27 | +Constraints: |
| 28 | +1 <= nums.length <= 105 |
| 29 | +nums[i] is either 0 or 1. |
| 30 | +=end |
| 31 | + |
| 32 | +# @param {Integer[]} nums |
| 33 | +# @return {Integer} |
| 34 | +def longest_subarray(nums) |
| 35 | + left = 0 |
| 36 | + right = 0 |
| 37 | + k = 1 |
| 38 | + max = 0 |
| 39 | + |
| 40 | + n = nums.size |
| 41 | + while right < n |
| 42 | + if nums[right] == 0 |
| 43 | + k -= 1 |
| 44 | + while k < 0 |
| 45 | + k += 1 if nums[left] == 0 |
| 46 | + left += 1 |
| 47 | + end |
| 48 | + end |
| 49 | + max = [max, right - left].max |
| 50 | + |
| 51 | + right += 1 |
| 52 | + end |
| 53 | + |
| 54 | + max |
| 55 | +end |
| 56 | + |
| 57 | +# **************** # |
| 58 | +# TEST # |
| 59 | +# **************** # |
| 60 | + |
| 61 | +require "test/unit" |
| 62 | +class Test_longest_subarray < Test::Unit::TestCase |
| 63 | + def test_ |
| 64 | + assert_equal 3, longest_subarray([1, 1, 0, 1]) |
| 65 | + assert_equal 5, longest_subarray([0, 1, 1, 1, 0, 1, 1, 0, 1]) |
| 66 | + assert_equal 2, longest_subarray([1, 1, 1]) |
| 67 | + end |
| 68 | +end |
0 commit comments