Read the official problem ↗ · View my C++ solution ↗
Start from the final state
Let C be the common value after all operations, and let xi be the number of times operation i is used. Operation i increments precisely those positions whose indices divide i. Therefore position j receives one increment from every selected operation whose index is a multiple of j.
For every position j:
Aj + Σi: j|i xi = C.
The variables do not form an arbitrary linear system. Multiples always point upward. If we process indices from N down to 1, every strict multiple of the current index has already been solved.
The reverse recurrence
Rearranging the equation for index i gives:
xi = C − Ai − Σj=2i,3i,… xj.
This is the key compression. Each xi is affine in the single unknown C. Write it as:
xi = piC + qi.
Substitution yields the reverse-divisor recurrence:
- pi = 1 − Σ pj over strict multiples j of i;
- qi = −Ai − Σ qj over those same multiples.
Nonnegativity becomes an interval
Operation counts must be nonnegative. Every index contributes one inequality:
piC + qi ≥ 0.
- If pi > 0, the inequality gives a lower bound on C.
- If pi < 0, it gives an upper bound.
- If pi = 0 and qi < 0, no solution exists.
Intersecting all bounds produces one feasible integer interval. The minimum valid final value is its lower endpoint.
Why the objective collapses
Position 1 divides every operation index, so it is incremented once by every operation. Its final equation is:
A1 + Σ xi = C.
Thus the total number of operations is exactly C − A1. Minimizing the operation count is the same as choosing the smallest feasible C.
Correctness outline
- The final-state equation accounts for every increment received by every position.
- Reverse traversal computes each operation count after all strict-multiple counts are known.
- The affine recurrence is algebraically identical to the final-state equations.
- The intersected inequalities are exactly the conditions that every operation count is nonnegative.
- The smallest feasible C minimizes C − A1, which equals the total number of operations.
Complexity
Index i visits its multiples, so the total work is O(N log N) by the harmonic-series bound. The coefficient arrays use O(N) memory.
What I would reuse
When an operation affects indices related by divisibility, containment, ancestry, or another partial order, look for a traversal that makes the system triangular. Then ask whether the remaining values can be parameterized by one small set of global variables. That representation often matters more than the eventual data structure.