★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-bflaaihi-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.git
For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time .github
Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.數組
Example1微信
Input: [1,0,5] Output: 3 Explanation: 1st move: 1 0 <-- 5 => 1 1 4 2nd move: 1 <-- 1 <-- 4 => 2 1 3 3rd move: 2 1 <-- 3 => 2 2 2
Example2spa
Input: [0,3,0] Output: 2 Explanation: 1st move: 0 <-- 3 0 => 1 2 0 2nd move: 1 2 --> 0 => 1 1 1
Example3code
Input: [0,2,0] Output: -1 Explanation: It's impossible to make all the three washing machines have the same number of dresses.
Note:htm
假設有 n 臺超級洗衣機放在同一排上。開始的時候,每臺洗衣機內可能有必定量的衣服,也多是空的。blog
在每一步操做中,你能夠選擇任意 m (1 ≤ m ≤ n) 臺洗衣機,與此同時將每臺洗衣機的一件衣服送到相鄰的一臺洗衣機。three
給定一個非負整數數組表明從左至右每臺洗衣機中的衣物數量,請給出能讓全部洗衣機中剩下的衣物的數量相等的最少的操做步數。若是不能使每臺洗衣機中衣物的數量相等,則返回 -1。
示例 1:
輸入: [1,0,5] 輸出: 3 解釋: 第一步: 1 0 <-- 5 => 1 1 4 第二步: 1 <-- 1 <-- 4 => 2 1 3 第三步: 2 1 <-- 3 => 2 2 2
示例 2:
輸入: [0,3,0] 輸出: 2 解釋: 第一步: 0 <-- 3 0 => 1 2 0 第二步: 1 2 --> 0 => 1 1 1
示例 3:
輸入: [0,2,0] 輸出: -1 解釋: 不可能讓全部三個洗衣機同時剩下相同數量的衣物。
提示:
1 class Solution { 2 func findMinMoves(_ machines: [Int]) -> Int { 3 var sum:Int = machines.reduce(0, +) 4 if sum % machines.count != 0 {return -1} 5 var res:Int = 0 6 var cnt:Int = 0 7 var avg:Int = sum / machines.count 8 for m in machines 9 { 10 cnt += m - avg 11 res = max(res, max(abs(cnt), m - avg)) 12 } 13 return res 14 } 15 }
1 class Solution { 2 func findMinMoves(_ machines: [Int]) -> Int { 3 var total = 0 4 for machine in machines { 5 total += machine 6 } 7 8 if (total % machines.count != 0) { 9 return -1 10 } else { 11 let average = total / machines.count 12 var dis = 0 13 var result = 0 14 15 for machine in machines { 16 let currentDis = machine - average 17 dis += currentDis 18 result = max(result, abs(dis)) 19 result = max(result, currentDis) 20 } 21 return result 22 } 23 } 24 }