โ Problem 1: Max Consecutive Ones
Given a binary array nums
, return the maximum number of consecutive 1s
in the array.
๐ง Approach:
We iterate through the array and keep a running count of consecutive 1
s. If we encounter a 0
, we reset the current count. We also track the maximum count found so far.
๐งฎ Time Complexity:
- O(n) โ We traverse the array once.
๐พ Space Complexity:
- O(1) โ Only constant extra space is used.
๐ป Code:
var findMaxConsecutiveOnes = function(nums) {
let current_Count = 0;
let max_Count = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 1) {
current_Count++;
if (current_Count > max_Count) {
max_Count = current_Count;
}
} else {
current_Count = 0;
}
}
return max_Count;
};
๐ฅ Example:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The maximum number of consecutive 1s is three.
โ Problem 2: Consecutive Characters
Given a string s
, return the power of the string. The power of the string is the maximum length of a substring that contains only one unique character.
๐ง Approach:
We iterate through the string, comparing each character with the previous one. If it's the same, increase the current count. Otherwise, reset the counter. Track the max count during the iteration.
๐งฎ Time Complexity:
- O(n) โ Single pass through the string.
๐พ Space Complexity:
- O(1) โ No additional data structures needed.
๐ป Code:
var maxPower = function(s) {
let current_Count = 0;
let max_Count = 0;
let char = '';
for (let i = 0; i < s.length + 1; i++) {
if (s[i] === char) {
current_Count++;
} else {
char = s[i];
current_Count = 1;
}
if (current_Count > max_Count) {
max_Count = current_Count;
}
}
return max_Count;
};
๐ฅ Example:
Input: "abbcccddddeeeeedcba"
Output: 5
Explanation: The longest sequence is "eeeee" with length 5.
โ Problem 3: Longest Continuous Increasing Subsequence (LCIS)
Given an unsorted array of integers nums
, return the length of the longest strictly increasing subsequence that is continuous.
๐ง Approach:
We iterate through the array and check if the current element is greater than the previous one. If so, increase the current length. Otherwise, reset. Keep track of the max length encountered.
๐งฎ Time Complexity:
-
O(n)
โ Single pass through the string.
๐พ Space Complexity:
-
O(1)
โ Constant space.
๐ป Code:
var findLengthOfLCIS = function(nums) {
let maxLen = 0;
let currentLen = 1;
if (nums.length === 0) return 0;
for (let i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
currentLen++;
} else {
if (currentLen > maxLen) {
maxLen = currentLen;
}
currentLen = 1;
}
}
return Math.max(maxLen, currentLen);
};
๐ฅ Example:
Input: [1,3,5,4,7]
Output: 3
Explanation: The LCIS is [1,3,5] with length 3.
Top comments (0)