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.
1#include <string.h>
2
3int maxPower(char * s) {
4 int max_power = 1, current_power = 1;
5 for(int i = 1; s[i] != '\0'; i++) {
6 if(s[i] == s[i-1]) {
7 current_power++;
8 } else {
9 if(current_power > max_power) {
10 max_power = current_power;
11 }
12 current_power = 1;
13 }
14 }
15 if(current_power > max_power) {
16 max_power = current_power;
17 }
18 return max_power;
19}
The code initializes two counters: max_power
and current_power
. As it iterates through the string, if consecutive characters are identical, it increments current_power
. If not, it updates max_power
if current_power
exceeds it, and resets current_power
.
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.
1function maxPower(s) {
2 const cache =
JavaScript's recursive approach takes advantage of the Memoization strategy using a Map. This prevents redundant evaluations for the same substring, efficiently computing the power of the string.