You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.html
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 .java
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.數組
Example1post
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
Example2url
Input: [0,3,0] Output: 2 Explanation: 1st move: 0 <-- 3 0 => 1 2 0 2nd move: 1 2 --> 0 => 1 1 1
Example3spa
Input: [0,2,0] Output: -1 Explanation: It's impossible to make all the three washing machines have the same number of dresses.
Note:code
這道題題給了咱們一堆工藤新一,噢不,是滾筒洗衣機。咱們有許多洗衣機,每一個洗衣機裏的衣服數不一樣,每一個洗衣機每次只容許向相鄰的洗衣機轉移一件衣服,問要多少次才能使全部洗衣機的衣服數相等。注意這裏的一次移動是說全部洗衣機均可以移動一件衣服到其相鄰的洗衣機。這道題的代碼量其實很少,難點是在於解題思路,難的是對問題的等價轉換等。博主也沒有作出這道題,博主想到了要先驗證衣服總數是否能整除洗衣機的數量,而後計算出每一個洗衣機最終應該放的衣服數,返回跟初始狀態衣服數之差的最大值,但這種解法是不對的,沒法經過這個test case [0, 0, 11, 5],最終每一個洗衣機會留4件衣服,我想的那方法會返回7,而後正確答案是8。想一想也是,若是這麼是這麼簡單的思路,這題怎麼會標記爲Hard呢,仍是圖樣圖森破啊。這裏直接參照大神Chidong的帖子來作,咱們就用上面那個例子,有四個洗衣機,裝的衣服數爲[0, 0, 11, 5],最終的狀態會變爲[4, 4, 4, 4],那麼咱們將兩者作差,獲得[-4, -4, 7, 1],這裏負數表示當前洗衣機還須要的衣服數,正數表示當前洗衣機多餘的衣服數。咱們要作的是要將這個差值數組每一項都變爲0,對於第一個洗衣機來講,須要四件衣服能夠從第二個洗衣機得到,那麼就能夠把-4移給二號洗衣機,那麼差值數組變爲[0, -8, 7, 1],此時二號洗衣機須要八件衣服,那麼至少須要移動8次。而後二號洗衣機把這八件衣服從三號洗衣機處得到,那麼差值數組變爲[0, 0, -1, 1],此時三號洗衣機還缺1件,就從四號洗衣機處得到,此時差值數組成功變爲了[0, 0, 0, 0],成功。那麼移動的最大次數就是差值數組中出現的絕對值最大的數字,8次,參見代碼以下:htm
class Solution { public: int findMinMoves(vector<int>& machines) { int sum = accumulate(machines.begin(), machines.end(), 0); if (sum % machines.size() != 0) return -1; int res = 0, cnt = 0, avg = sum / machines.size(); for (int m : machines) { cnt += m - avg; res = max(res, max(abs(cnt), m - avg)); } return res; } };
參考資料:blog
https://discuss.leetcode.com/topic/79938/super-short-easy-java-o-n-solutionthree
https://discuss.leetcode.com/topic/79923/c-16ms-o-n-solution-with-trivial-proof