Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Longest subarray which only contains strictly increasing numbers JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument.
The function should then return the length of the longest continuous subarray from the array that only contains elements in a strictly increasing order.
A strictly increasing sequence is the one in which any succeeding element is greater than all its preceding elements.
Example
const arr = [5, 7, 8, 12, 4, 56, 6, 54, 89];
const findLongest = (arr) => {
if(arr.length == 0) {
return 0;
};
let max = 0;
let count = 0;
for(let i = 1; i < arr.length; i++) {
if(arr[i] > arr[i-1]) {
count++;
} else {
count = 0;
}
if(count > max) {
max = count;
}
}
return max + 1;
};
console.log(findLongest(arr));
Output
And the output in the console will be ?
4
How It Works
Let's trace through the algorithm with our example array [5, 7, 8, 12, 4, 56, 6, 54, 89]:
- Start with
count = 0andmax = 0 - Compare adjacent elements: 7 > 5, so count becomes 1
- 8 > 7, count becomes 2
- 12 > 8, count becomes 3, max becomes 3
- 4 < 12, count resets to 0
- 56 > 4, count becomes 1
- 6 < 56, count resets to 0
- Continue until end...
The longest strictly increasing subarray is [5, 7, 8, 12] with length 4.
Alternative Approach
Here's a more explicit version that tracks the actual subarray positions:
const findLongestDetailed = (arr) => {
if(arr.length <= 1) return arr.length;
let maxLength = 1;
let currentLength = 1;
let bestStart = 0;
let currentStart = 0;
for(let i = 1; i < arr.length; i++) {
if(arr[i] > arr[i-1]) {
currentLength++;
} else {
if(currentLength > maxLength) {
maxLength = currentLength;
bestStart = currentStart;
}
currentLength = 1;
currentStart = i;
}
}
// Check final sequence
if(currentLength > maxLength) {
maxLength = currentLength;
bestStart = currentStart;
}
console.log(`Longest subarray: [${arr.slice(bestStart, bestStart + maxLength)}]`);
return maxLength;
};
const testArray = [5, 7, 8, 12, 4, 56, 6, 54, 89];
console.log(`Length: ${findLongestDetailed(testArray)}`);
Longest subarray: [5,7,8,12] Length: 4
Conclusion
The algorithm efficiently finds the longest strictly increasing subarray in O(n) time complexity by tracking consecutive increases and maintaining the maximum length found so far.
