【leetcode】1493. Longest Subarray of 1's After Deleting One Element

题目如下:

Given a binary array nums, you should delete one element from it.

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. 

Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.

Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
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].

Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.

Example 4:

Input: nums = [1,1,0,0,1,1,1,0,1]
Output: 4

Example 5:

Input: nums = [0,0,0]
Output: 0

Constraints:

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1.

解题思路:分别从左往右和从右往左边路nums,记录每个下标从左往右和从右往左的连续1的个数。最后计算出从左往右和从右往左的连续1的个数的和的最大值即可。

代码如下:

class Solution(object):
    def longestSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        left = []
        right = []
        count_1 = 0
        for i in nums:
            if i == 1:
                count_1 += 1
                left.append(count_1)
            else:
                left.append(count_1)
                count_1 = 0

        count_1 = 0
        for i in nums[::-1]:
            if i == 1:
                count_1 += 1
                right.insert(0,count_1)
            else:
                right.insert(0, count_1)
                count_1 = 0
        res = -float('inf')
        for i in range(len(nums)):
            if nums[i] == 0:
                res = max(res,left[i] + right[i])

        return res if res != -float('inf') else len(nums) - 1
原文地址:https://www.cnblogs.com/seyjs/p/13217781.html