This problem looks busy at first, but the accepted solution is built around one steady invariant. For 674. Longest Continuous Increasing Subsequence, the solution in this repository is mainly a sliding window solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: sliding window.
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 findLengthOfLCIS.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- 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:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
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)O(N), where NN is the length of nums. We perform one loop through nums.
- Space: O(1)O(1), the space used by anchor and ans.
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 16 ms, faster than 98.15% of C++ online submissions for Longest Continuous Increasing Subsequence.
02//Memory Usage: 9.3 MB, less than 98.08% of C++ online submissions for Longest Continuous Increasing Subsequence.
03
04class Solution {
05public:
06 int findLengthOfLCIS(vector<int>& nums) {
07 if(nums.size() == 0) return 0;
08
09 int l = 1;
10 int ans = INT_MIN;
11
12 for(int i = 1; i < nums.size(); i++){
13 if(nums[i] - nums[i-1] <= 0){
14 ans = max(ans, l);
15 l = 1;
16 }else{
17 l++;
18 }
19 // cout << l << endl;
20 }
21 ans = max(ans, l);
22 // cout << endl;
23
24 return ans;
25 }
26};
27
28/**
29Approach #1: Sliding Window [Accepted]
30**/
31
32/**
33Complexity Analysis
34
35Time Complexity: O(N)O(N), where NN is the length of nums. We perform one loop through nums.
36
37Space Complexity: O(1)O(1), the space used by anchor and ans.
38**/
39
40/**
41class Solution {
42public:
43 int findLengthOfLCIS(vector<int>& nums) {
44 int ans = 0, anchor = 0;
45 for(int i = 0; i < nums.size(); i++){
46 //restart when series be non-increasing
47 if(i > 0 && nums[i] <= nums[i-1]) anchor = i;
48 ans = max(ans, i - anchor + 1);
49 }
50 return ans;
51 }
52};
53**/
Cost