| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.TakeKOfEachCharacterFromLeftAndRight; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class TakeKOfEachCharacterFromLeftAndRightSlidingWindow : ITakeKOfEachCharacterFromLeftAndRight |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int TakeCharacters(string s, int k) |
| 2 | 25 | | { |
| 2 | 26 | | var count = new int[3]; |
| | 27 | |
|
| 32 | 28 | | foreach (var c in s) |
| 13 | 29 | | { |
| 13 | 30 | | count[c - 'a']++; |
| 13 | 31 | | } |
| | 32 | |
|
| 7 | 33 | | if (count.Any(c => c < k)) |
| 1 | 34 | | { |
| 1 | 35 | | return -1; |
| | 36 | | } |
| | 37 | |
|
| 1 | 38 | | var window = new int[3]; |
| 1 | 39 | | var left = 0; |
| 1 | 40 | | var maxWindow = 0; |
| | 41 | |
|
| 26 | 42 | | for (var right = 0; right < s.Length; right++) |
| 12 | 43 | | { |
| 12 | 44 | | window[s[right] - 'a']++; |
| | 45 | |
|
| 24 | 46 | | while (left <= right && (count[0] - window[0] < k || count[1] - window[1] < k || count[2] - window[2] < k)) |
| 12 | 47 | | { |
| 12 | 48 | | window[s[left] - 'a']--; |
| | 49 | |
|
| 12 | 50 | | left++; |
| 12 | 51 | | } |
| | 52 | |
|
| 12 | 53 | | maxWindow = Math.Max(maxWindow, right - left + 1); |
| 12 | 54 | | } |
| | 55 | |
|
| 1 | 56 | | return s.Length - maxWindow; |
| 2 | 57 | | } |
| | 58 | | } |