1785. 构成特定和须要添加的最少元素(难度:中等)

程序员 2024-10-1 13:48:02 63 0 来自 中国
标题链接:https://leetcode.cn/problems/minimum-elements-to-add-to-form-a-given-sum/
标题形貌:

给你一个整数数组 nums ,和两个整数 limit 与 goal 。数组 nums 有一条告急属性:abs(nums) <= limit 。
返回使数组元素总和即是 goal 所须要向数组中添加的 最少元素数目 ,添加元素 不应改变 数组中 abs(nums) <= limit 这一属性。
留意,假如 x >= 0 ,那么 abs(x) 即是 x ;否则,即是 -x 。
示例 1:
输入:nums = [1,-1,1], limit = 3, goal = -4输出:2表明:可以将 -2 和 -3 添加到数组中,数组的元素总和变为 1 - 1 + 1 - 2 - 3 = -4 。示例 2:
输入:nums = [1,-10,9,1], limit = 100, goal = 0输出:1提示:

  • 1 <= nums.length <= 105
  • 1 <= limit <= 106
  • -limit <= nums <= limit
  • -109 <= goal <= 109
解法:模仿

盘算出nums 的和与goal的差距temp,然后除以limit向上取整。
向上取整:

  • 若刚好整除的话,result = temp / limit。
  • 若不刚好整除的话,result = temp / limit + 1。
综上:result = (temp + limit - 1) / limit。
代码:
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 16:55, Processed in 0.141975 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表