Sponsored
Sponsored
The Sliding Window approach iterates through the string keeping track of the current character streak. When the character changes, update the maximum streak length if the current streak is larger. Reset the current streak counter for the new character.
Time Complexity: O(n) since each character is processed once.
Space Complexity: O(1) as no extra space is used aside from variables.
1function maxPower(s) {
2 let max_power = 1, current_power = 1;
3 for (let i = 1; i < s.length; i++) {
4 if (s[i] === s[i - 1]) {
5 current_power++;
6 } else {
7 max_power = Math.max(max_power, current_power);
8 current_power = 1;
9 }
10 }
11 return Math.max(max_power, current_power);
12}
Uses JavaScript's array-like string handling to iterate and determine the string's power by counting consecutive characters.
The recursive approach utilizes memoization to avoid repetitive calculations as it navigates the string, exploring all possibilities for consecutive substrings.
Time Complexity: O(n)
Space Complexity: O(n) due to recursion call stack and cache storage.
1def maxPower(s: str) -> int:
2
Python's recursive solution uses a cache to store already computed results, progressively calculating the power from the leftmost to the rightmost position of the string. It returns the maximum possible achieved by counting same consecutive characters.