调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
困难
相关标签
相关企业
提示

给你一个整数数组 nums 和两个整数 cost1 和 cost2 。你可以执行以下 任一 操作 任意 次:

  • nums 中选择下标 i 并且将 nums[i] 增加 1 ,开销为 cost1
  • 选择 nums 中两个 不同 下标 i 和 j ,并且将 nums[i] 和 nums[j] 都 增加 1 ,开销为 cost2 。

你的目标是使数组中所有元素都 相等 ,请你返回需要的 最小开销 之和。

由于答案可能会很大,请你将它对 109 + 7 取余 后返回。

 

示例 1:

输入:nums = [4,1], cost1 = 5, cost2 = 2

输出:15

解释:

执行以下操作可以使数组中所有元素相等:

  • 将 nums[1] 增加 1 ,开销为 5 ,nums 变为 [4,2] 。
  • 将 nums[1] 增加 1 ,开销为 5 ,nums 变为 [4,3] 。
  • 将 nums[1] 增加 1 ,开销为 5 ,nums 变为 [4,4] 。

总开销为 15 。

示例 2:

输入:nums = [2,3,3,3,5], cost1 = 2, cost2 = 1

输出:6

解释:

执行以下操作可以使数组中所有元素相等:

  • 将 nums[0] 和 nums[1] 同时增加 1 ,开销为 1 ,nums 变为 [3,4,3,3,5] 。
  • 将 nums[0] 和 nums[2] 同时增加 1 ,开销为 1 ,nums 变为 [4,4,4,3,5] 。
  • 将 nums[0] 和 nums[3] 同时增加 1 ,开销为 1 ,nums 变为 [5,4,4,4,5] 。
  • 将 nums[1] 和 nums[2] 同时增加 1 ,开销为 1 ,nums 变为 [5,5,5,4,5] 。
  • 将 nums[3] 增加 1 ,开销为 2 ,nums 变为 [5,5,5,5,5] 。

总开销为 6 。

示例 3:

输入:nums = [3,5,3], cost1 = 1, cost2 = 3

输出:4

解释:

执行以下操作可以使数组中所有元素相等:

  • 将 nums[0] 增加 1 ,开销为 1 ,nums 变为 [4,5,3] 。
  • 将 nums[0] 增加 1 ,开销为 1 ,nums 变为 [5,5,3] 。
  • 将 nums[2] 增加 1 ,开销为 1 ,nums 变为 [5,5,4] 。
  • 将 nums[2] 增加 1 ,开销为 1 ,nums 变为 [5,5,5] 。

总开销为 4 。

 

提示:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 106
  • 1 <= cost1 <= 106
  • 1 <= cost2 <= 106
通过次数
2.3K
提交次数
10.9K
通过率
21.3%

相关标签

相关企业

提示 1
How can you determine the minimum cost if you know the maximum value in the array once all values are made equal?

提示 2
If cost2 > cost1 * 2, we should just use cost1 to change all the values to the maximum one.

提示 3
Otherwise, it's optimal to choose the smallest two values and use cost2 to increase both of them.

提示 4
Since the maximum value is known, calculate the required increases to equalize all values, instead of naively simulating the operations.

提示 5
There are not a lot of candidates for the maximum; we can try all of them and choose which uses the minimum number of operations.

评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
运行和提交代码需要登录
nums =
[4,1]
cost1 =
5
cost2 =
2
Source