Member-only story
Here’s the breakdown of how I solved this problem on LeetCode. The problem wants you to find the maximum amount of consecutive characters in a given string.
I set up a for
loop to iterate over each character and then determined that over each pass I needed to keep track of the current maximum count, called maxCount
and the current running total, called currentCount
. For each iteration through the loop, that’s all that would need to be accounted for.
Within the loop, I knew that I would have to compare the current character being observed with the previous character. If they match, I’d add one to currentCount
otherwise I’d just reset currentCount
to one. At the end of each loop I set maxCount
to either equal itself or currentCount
— whichever is greater. Outside the loop I was sure to return maxCount
as the final result.
In terms of space complexity, we aren’t storing and data objects, so we have a space complexity of O(1). In terms of time complexity, we’re only using one for
loop that iterates over each character in the given string — so we have a time complexity of O(n), where n is the length of given string s.
See my full solution below:
var maxPower = function(s) {
let maxCount = 0
let currentCount = 1
for(let i = 1; i <= s.length; i++){
let char = s[i]
let lastChar = s[i - 1]
if(char === lastChar){
currentCount += 1
} else {
currentCount = 1
}
maxCount = Math.max(maxCount, currentCount)
}
return maxCount
};