Given an array of numbers, find the length of the longest contiguous subarray such that every element in the subarray is strictly greater than its previous element. The solution should run in O(n) time.
Also, this question is similar to Subarray With Given Sum. In this post, I’m going to cover topics like “sliding window”, dynamic programming, time/space complexity and so on.
The most straightforward approach is to examine every possible subarray and determine if it is strictly increasing. For each starting index, we check all possible ending indices and keep track of the longest increasing subarray found. While this method is simple and does not require extra memory, it is inefficient for large arrays.
Instead of checking all possible subarrays, we can scan the array once and keep track of the length of the current increasing subarray. Whenever the sequence breaks, we reset the length counter. This way, we efficiently find the longest increasing subarray in a single pass.
classSolution {
public:int longestIncreasingSubarray(vector<int>& nums) {
int ans =1, len =1;
for (int i =1; i < nums.size(); ++i) {
if (nums[i] > nums[i-1]) len++;
else {
ans = max(ans, len);
len =1;
}
}
returnmax(ans, len);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funclongestIncreasingSubarray(nums []int) int {
ans, len:=1, 1fori:=1; i < len(nums); i++ {
ifnums[i] > nums[i-1] {
len++ } else {
iflen > ans {
ans = len }
len = 1 }
}
iflen > ans {
ans = len }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
publicintlongestIncreasingSubarray(int[] nums) {
int ans = 1, len = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i]> nums[i-1]) len++;
else {
ans = Math.max(ans, len);
len = 1;
}
}
return Math.max(ans, len);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funlongestIncreasingSubarray(nums: IntArray): Int {
var ans = 1var len = 1for (i in1 until nums.size) {
if (nums[i] > nums[i-1]) len++else {
ans = maxOf(ans, len)
len = 1 }
}
return maxOf(ans, len)
}
}
1
2
3
4
5
6
7
8
9
10
deflongest_increasing_subarray(nums: list[int]) -> int:
ans =1 len_ =1for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
len_ +=1else:
ans = max(ans, len_)
len_ =1return max(ans, len_)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnlongest_increasing_subarray(nums: Vec<i32>) -> i32 {
letmut ans =1;
letmut len =1;
for i in1..nums.len() {
if nums[i] > nums[i-1] {
len +=1;
} else {
ans = ans.max(len);
len =1;
}
}
ans.max(len)
}
}
Instead of checking every possible subarray, we can use a sliding window to efficiently track the longest increasing segment. By maintaining two pointers, we expand the window as long as the sequence is increasing, and reset the window when the sequence breaks. This approach ensures we only scan the array once and always keep track of the longest valid window.