Sponsored
Sponsored
This approach involves using prefix sums to count the number of 'b's seen until each index and adjusting to track the potential number of deletions to ensure a balanced string.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), since we're using constant space.
1using System;
2
3public class MinDeletionsBalanced {
4 public static int MinDeletionsToMakeBalanced(string s) {
5 int totalB = 0;
6
7 foreach (char c in s) {
8 if (c == 'b') totalB++;
9 }
10
11 int minDeletions = totalB;
12 int currentA = 0, currentB = 0;
13
14 foreach (char c in s) {
15 if (c == 'a') {
16 currentA++;
17 } else if (c == 'b') {
18 currentB++;
19 minDeletions = Math.Min(minDeletions, currentA + (totalB - currentB));
20 }
21 }
22
23 return minDeletions;
24 }
25
26 public static void Main() {
27 string s = "aababbab";
28 Console.WriteLine(MinDeletionsToMakeBalanced(s)); // Output: 2
29 }
30}
The C# solution similarly uses a straightforward approach with a focus on readability and functional use of loops to track the count of 'a's and 'b's to minimize deletions efficiently.