前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >453. Minimum Moves to Equal Array Elements

453. Minimum Moves to Equal Array Elements

作者头像
Dylan Liu
发布2019-07-01 14:05:56
3340
发布2019-07-01 14:05:56
举报
文章被收录于专栏:dylanliudylanliu

Description

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

Example:

Input:
[1,2,3]

Output:
3

Explanation:
Only three moves are needed (remember each move increments two elements):

[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

Solution

数学题。 每次n-1个元素加1,相当于每次只有一个元素-1,相等就是都减到最小的元素。

func minMoves(nums []int) int {
    size := len(nums)
    smallest := nums[0]
    total := 0
    
    for _,val := range nums[1:] {
        if smallest > val {
            total += smallest
            smallest = val
        } else {
            total += val
        }
    }
    
    return total - (size -1) * smallest
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Solution
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档