Leetcode 1785. Minimum Elements to Add to Form a Given Sum
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1785. Minimum Elements to Add to Form a Given Sum相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,根据题意,需要先数组求和,然后再求跟目标的差值,为了添加最少数量的数字,因此每次都应添加极限数值,题目变成了算除法并对余数取整。
- Version 1
class Solution:
def minElements(self, nums: List[int], limit: int, goal: int) -> int:
total = sum(nums)
diff = goal - total
count = ceil(abs(diff) / limit)
return count
Reference
以上是关于Leetcode 1785. Minimum Elements to Add to Form a Given Sum的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode: Minimum Moves to Equal Array Elements