I like to read this solution as a small machine: keep the useful information, throw away the noise. For 495. Teemo Attacking, 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 is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are findPoisonedDuration.
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), space: O(1)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 92 ms, faster than 92.37% of C++ online submissions for Teemo Attacking.
02//Memory Usage: 26 MB, less than 37.20% of C++ online submissions for Teemo Attacking.
03class Solution {
04public:
05 int findPoisonedDuration(vector<int>& timeSeries, int duration) {
06 int ans = 0;
07 int cur_end;
08 int last_end = INT_MIN;
09
10 for(const int& start : timeSeries){
11 cur_end = start+duration-1;
12 if(last_end >= start){
13 ans += (cur_end - last_end);
14 }else{
15 ans += duration;
16 }
17
18 last_end = cur_end;
19 // cout << last_end << ", " << ans << endl;
20 }
21
22 return ans;
23 }
24};
25
26//Approach 1: One pass
27//Runtime: 92 ms, faster than 92.37% of C++ online submissions for Teemo Attacking.
28//Memory Usage: 26.2 MB, less than 10.17% of C++ online submissions for Teemo Attacking.
29//time: O(N), space: O(1)
30class Solution {
31public:
32 int findPoisonedDuration(vector<int>& timeSeries, int duration) {
33 int n = timeSeries.size();
34 //edge case
35 if(n == 0) return 0;
36
37 int ans = 0;
38
39 for(int i = 1; i < n; ++i){
40 ans += min(duration, timeSeries[i]-timeSeries[i-1]);
41 }
42
43 //last attack: duration
44 return ans + duration;
45 }
46};
Cost