Member-only story

Leetcode 1493: Longest Subarray of 1’s After Deleting One Element

Pierre-Marie Poitevin
2 min readJun 28, 2020

--

In this Leetcode problem, we want to find the longest possible chain of ones when we remove one element of the array.

Problem statement

Solution

A couple of ideas to find the solution:

  • At the end of each series of 1s we want to compute the chain of maximum length that ends with that last 1 by removing an element of the array.
  • That chain length is the length of the current chain current and the length of the previous chain previous if previous and current chains were only separated with 1 zero. If they were separated by 2 or more zeros, then the chain length is only current
  • If we never encounter a zero, then the result is n — 1
  • At the end of the whole loop, we need to recompute max in the case the last chain of 1s and previous chain of 1s have the maximum length

Here is the full code following these ideas:

class Solution {
public int longestSubarray(int[] nums) {
int n = nums.length;
// if hasZero stays false return n - 1
boolean hasZero = false;
// current length 1 chain
int current = 0;
// current length 0 chain
int zeros = 0;
// previous length length 1 chain
int previous = 0;
//…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet