zoukankan      html  css  js  c++  java
  • Leetcode 1590. Make Sum Divisible by P

    Description

    Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.
    
    Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.
    
    A subarray is defined as a contiguous block of elements in the array.
    

    Example

    Input: nums = [3,1,4,2], p = 6
    Output: 1
    Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.
    

    code

    class Solution(object):
        def minSubarray(self, nums, p):
            """
            :type nums: List[int]
            :type p: int
            :rtype: int
            """
            memo = {}
            presum, L, N = 0, float('inf'), len(nums)
            remain = sum(nums) % p
            if remain == 0:
                return 0
            
            memo[0] = -1
            for i, v in enumerate(nums):
                if v == remain:
                    return 1
                
                presum += v
                presum %= p
                
                if presum - remain in memo:
                    L = min(L, i - memo[presum-remain])
                if presum + p -remain in memo:
                    L = min(L, i - memo[presum+p-remain])
            
                memo[presum] = i
            if L == N:
                return -1
            
            return -1 if L == float('inf') else L
    
    
    
    本题调试了很久,原因有2点。第一点,我同余计算总是出错(数学不好啊)。第二点,memo【0】 = 1 这个初始化条件一直没有想到
    
  • 相关阅读:
    NOIP 模拟 $94; m 超级加倍$
    NOIP 模拟 $94; m 欢乐豆$
    NOIP 模拟 $94; m 叁仟柒佰万$
    NOIP 模拟 $94; m 开挂$
    NOIP 模拟 $92; m 优美的旋律$
    NOIP 模拟 $92; m 翻转游戏$
    NOIP 模拟 $92; m 石子合并$
    NOIP 模拟 $90; m 校门外歪脖树上的鸽子$
    NOIP 模拟 $90; m 混乱邪恶$
    NOIP 模拟 $90; m 快速排序$
  • 原文地址:https://www.cnblogs.com/tmortred/p/14492858.html
Copyright © 2011-2022 走看看