#674
Longest Continuous Increasing Subsequence
EasyArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a single pass through the array to track the length of the current increasing sequence. This reduces the time complexity significantly by avoiding nested loops.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to keep track of the current length of the increasing sequence and the maximum length found.
- 2Step 2: Iterate through the array starting from the second element.
- 3Step 3: If the current element is greater than the previous one, increment the current length; otherwise, reset the current length to 1.
- 4Step 4: Update the maximum length if the current length exceeds it.
solution.py12 lines
1def longest_increasing_subsequence(nums):
2 if not nums:
3 return 0
4 max_length = 1
5 current_length = 1
6 for i in range(1, len(nums)):
7 if nums[i] > nums[i - 1]:
8 current_length += 1
9 else:
10 current_length = 1
11 max_length = max(max_length, current_length)
12 return max_lengthℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array. The space complexity is O(1) since we are using a fixed number of variables.
- 1The sequence must be strictly increasing, meaning duplicates reset the count.
- 2Continuous means elements must be adjacent in the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.