
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Super Washing Machines in C++
Suppose we have n super washing machines on a row. Initially, each washing machine has some dresses or empty. Now, for each move, we can 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. Suppose we have one integer array representing the number of dresses in each washing machine from left to right on the row, we should find the minimum number of moves to make all the washing machines have the same number of clothes. If it is not possible to do, then return -1.
So when the input is like [1,0,5], then the output will be 3, this is because send 5 to 0, so the distribution will be [1, 1, 4], then middle 1 to left one, 4 to 1, then it will be [2,1,3], then 2 to 1, so finally it will be [2,2,2]
To solve this, we will follow these steps −
- sum := sum of all elements of v
- n := size of v
- if sum mod n is not equal to 0, then −
- return -1
- req := sum / n, ret := 0, extra := 0
- for initialize i := 0, when i < n, update (increase i by 1), do −
- x := v[i]
- extra := extra + (x - req)
- ret := maximum of {ret, x - req, |extra|
- return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int findMinMoves(vector<int>& v) { int sum = accumulate(v.begin(), v.end(), 0); int n = v.size(); if(sum % n != 0) return -1; int req = sum / n; int ret = 0; int extra = 0; for(int i = 0; i < n; i++){ int x = v[i]; extra +=( x - req); ret = max({ret, x - req, abs(extra)}); } return ret; } }; main(){ Solution ob; vector<int> v = {2,1,6}; cout << (ob.findMinMoves(v)); }
Input
{2,1,6}
Output
3
- Related Articles
- Super Pow in C++
- Super Palindromes in C++
- Super Prime in c programming
- Super Ugly Number in C++
- Super Egg Drop in C++
- Equivalent of Java Super Keyword in C#
- Simple Machines
- super keyword in Java
- Super Key in RDBMS
- Super keyword in JavaScript?
- Super constructor in Dart Programming
- Super keyword in Dart Programming
- C++ Program to find out the super vertices in a graph
- What is super() function in JavaScript?
- What are simple machines?
