Opening the reading…
Opening the reading…
GREEDY › PART I
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Suppose the current maximum value is x. Choosing any smaller value can score at most x - 1, while choosing x scores x and immediately changes that element to x + 1. The changed element is therefore still at least as large as every element that was not chosen, so choosing it again is never worse than switching to another element.
If the initial maximum is M, the scores from the k operations are M, M + 1, M + 2, and so on through M + k - 1. Their sum is kM + k(k - 1) / 2. The whole problem therefore reduces to finding the initial maximum; no simulation or sorting is needed.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The maximum scan examines each of the n input elements once. The final formula uses a fixed number of arithmetic operations, so it adds O(1) work and nothing is revisited. |
| Space | O(1) extra | Only maxVal and a few arithmetic variables are needed. The input array is not copied, and there is no returned collection whose storage would need to be counted; the bound does not degrade with any input shape. |
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int maximizeSum(vector<int>& nums, int k) {
int maxVal = *max_element(nums.begin(), nums.end());
return k * maxVal + k * (k - 1) / 2;
}
};The important line is the return expression. The term k * maxVal counts the starting value once for each operation, while k * (k - 1) / 2 sums the increases added before each later selection. The increase offsets are 0, 1, 2, through k - 1, so using k * k / 2 would include one extra increase and produce the wrong score.