../ Competitive Programming
-rw-r--r--aguang757 B1 min read

Leet Code Daily 2024-06-16 - Patching Array

Solution

Assuming we have completed range [1, x] and the next given but not used number is y,

  • If y <= x + 1, then we just use yy and expand the range to [1, x + y].
  • Otherwise, we must patch a new number x + 1, and the new range would be [1, x + x + 1].

Code

c++
class Solution {
public:
    int minPatches(vector<int>& nums, int n) {
        int i = 0, ans = 0;
        for (long long r = 0; r < n;) {
            if (i < nums.size() && nums[i] <= r + 1) {
                r += nums[i++];
            } else {
                r += r + 1;
                ans++;
            }
        }
        return ans;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window