I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1431. Kids With the Greatest Number of Candies, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are kidsWithCandies.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Kids With the Greatest Number of Candies.
02//Memory Usage: 9.2 MB, less than 100.00% of C++ online submissions for Kids With the Greatest Number of Candies.
03class Solution {
04public:
05 vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
06 int maxCandy = *max_element(candies.begin(), candies.end());
07 int n = candies.size();
08
09 vector<bool> ans(n);
10
11 for(int i = 0; i < n; i++){
12 ans[i] = (maxCandy - candies[i] <= extraCandies);
13 }
14
15 return ans;
16 }
17};
Cost