C++ One-pass solution, try to avoid summing overflow


  • 0
    A

    Accumulate the moves on the go instead of summing all elements up. The latter could easily overflow.

    84 / 84 test cases passed
    Status: Accepted
    Runtime: 63 ms

    class Solution {
    public:
        int minMoves(vector<int>& nums) {
            uint diff = 0;
            for (int i = 1, ii = nums.size(), min = nums[0]; i < ii; i++) {
                if (nums[i] < min) {
                    diff += (min - nums[i]) * i;
                    min = nums[i];
                } else diff += nums[i] - min;
            }
            return diff;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.