just calculate the number of moves needed for each element to equal the maximum value in the array.
code link to code
class Solution {
public:
int minMoves(vector<int>& nums) {
int sum{};
int mx{};
for (int num : nums) {
sum += num;
mx = max(num, mx);
}
return mx * static_cast<int>(nums.size()) - sum;
}
};complexity link to complexity
- Time:
O(n)- Space:
O(1)
time taken link to time taken
- 1 minute and 10 seconds