If we have a number array and a desired range of values, we have chance to operate a pair of numbers every time with multiple times - we are able to give a number a plus and give another number a minus at the same time.
So, how many times do we need to balance all numbers into the range? Return -1 if we have no way to achieve it.
classSolution { public: // Boundary: [left, right] staticintminimum_time_to_balance(const std::vector<int>& values, int left, int right){ int sum = std::accumulate(values.begin(), values.end(), 0); int n = values.size();
if (sum < left * n || sum > right * n) { return-1; }
int need_to_plus = 0, need_to_minus = 0; for (int value : values) { if (value < left) { need_to_plus += left - value; } elseif (value > right) { need_to_minus += value - right; } }
However, what if the balance between the pair of numbers is unequal? For example, when we give a number a plus, we have to give another number 2 minus. In this way, the balance of transformation is unequal.
staticintdivide_by_lower(int dividend, int divisor){ return dividend / divisor; } };
More Advanced: Unequal Balance of General Rate
What if the balance rate between the pair of numbers is more general? For example, when we give a number n plus (define it as plus_factor), we have to give another number m minus (define it as minus_factor).
classSolution { public: // Boundary: [left, right] staticintminimum_time_to_balance(const std::vector<int>& values, int left, int right, int plus_factor, int minus_factor){ int min_need_plus_steps = 0, min_need_minus_steps = 0; int max_can_plus_steps = 0, max_can_minus_steps = 0; for (int value : values) { if (value < left) { int min_need_plus_step = divide_by_upper(left - value, plus_factor);
int max_can_plus_step = divide_by_lower(right - value, plus_factor); if (min_need_plus_step > max_can_plus_step) { return-1; } min_need_plus_steps += min_need_plus_step; max_can_plus_steps += max_can_plus_step; } elseif (value > right) { int min_need_minus_step = divide_by_upper(value - right, minus_factor); int max_can_minus_step = divide_by_lower(value - left, minus_factor); if (min_need_minus_step > max_can_minus_step) { return-1; } min_need_minus_steps += min_need_minus_step; max_can_minus_steps += max_can_minus_step; } else { // left <= value <= right