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.
1public class Solution {
2 public int MaxPower(string s) {
3 int max_power = 1;
4 int current_power = 1;
5 for(int i = 1; i < s.Length; i++) {
6 if(s[i] == s[i-1]) {
7 current_power++;
8 } else {
9 max_power = Math.Max(max_power, current_power);
10 current_power = 1;
11 }
12 }
13 return Math.Max(max_power, current_power);
14 }
15}
In C#, utilizes loop logic to maintain a count of consecutive characters, applying a maximum calculation when the streak breaks.
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.