702649. Longest Increasing subarray
Easy
Longest Increasing Subarray
Summary
Given an array of integers, find the length of the longest increasing subarray. A subarray is a contiguous part of the original array.
This problem involves working with arrays and finding the longest increasing sequence within it. The key concept here is to identify the longest increasing subsequence in the given array.
Detailed Explanation
The approach to solve this problem is simple: iterate over the array, keep track of the current increasing subarray, and update the maximum length when necessary.
Here's a step-by-step breakdown:
- Initialize
max_lengthto 1 (the smallest possible subarray) andcurrent_lengthto 1. - Iterate over the array:
- For each element, check if it is greater than the previous element (if this is the first element or there is no previous element).
- If the current element is not increasing, update
max_lengthwith the current length and resetcurrent_lengthto 1. - If the current element is increasing, increment
current_length.
- Update
max_lengthwith the maximum of the current length andmax_length.
Time complexity: O(n), where n is the number of elements in the array.
Space complexity: O(1), as we only use a few variables to keep track of the subarray lengths.
Optimized Solutions
Java
public int longestIncreasingSubarray(int[] arr) {
int max_length = 1;
int current_length = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[i - 1]) {
current_length++;
} else {
max_length = Math.max(max_length, current_length);
current_length = 1;
}
}
return Math.max(max_length, current_length);
}