Middle+
Fix the method that returns the maximum length of a sequence in which each subsequent element increases by 1, in a given array of integers. If the list consists of 1 element, then the length of the sequence is 1.
sobes.tech AI
Answer from AI
Task — find the maximum length of a sequence in an array where each subsequent element increases exactly by 1.
Example of a corrected method in JavaScript:
function maxIncreasingSequenceLength(arr) {
if (arr.length === 0) return 0;
if (arr.length === 1) return 1;
let maxLen = 1;
let currentLen = 1;
for (let i = 1; i < arr.length; i++) {
if (arr[i] === arr[i - 1] + 1) {
currentLen++;
if (currentLen > maxLen) {
maxLen = currentLen;
}
} else {
currentLen = 1;
}
}
return maxLen;
}
// Example usage:
console.log(maxIncreasingSequenceLength([1, 2, 3, 5, 6, 7, 8, 10])); // 4 (sequence 5,6,7,8)
console.log(maxIncreasingSequenceLength([10])); // 1
Logic:
- Iterate through the array starting from the first element.
- If the current element equals the previous element + 1, increase the current sequence counter.
- Otherwise, reset the counter.
- Track the maximum length of the sequence.
This way, we find the maximum length of a strictly increasing sequence with a step of 1.