| | 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.GetEqualSubstringsWithinBudget; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class GetEqualSubstringsWithinBudgetSlidingWindow : IGetEqualSubstringsWithinBudget |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="s"></param> |
| | 22 | | /// <param name="t"></param> |
| | 23 | | /// <param name="maxCost"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int EqualSubstring(string s, string t, int maxCost) |
| 7 | 26 | | { |
| 7 | 27 | | var maxLength = 0; |
| 7 | 28 | | var cost = 0; |
| 7 | 29 | | var left = 0; |
| 7 | 30 | | var right = 0; |
| | 31 | |
|
| 48 | 32 | | while (right < s.Length) |
| 41 | 33 | | { |
| 41 | 34 | | cost += Math.Abs(s[right] - t[right]); |
| | 35 | |
|
| 67 | 36 | | while (cost > maxCost) |
| 26 | 37 | | { |
| 26 | 38 | | cost -= Math.Abs(s[left] - t[left]); |
| | 39 | |
|
| 26 | 40 | | left++; |
| 26 | 41 | | } |
| | 42 | |
|
| 41 | 43 | | maxLength = Math.Max(maxLength, right - left + 1); |
| | 44 | |
|
| 41 | 45 | | right++; |
| 41 | 46 | | } |
| | 47 | |
|
| 7 | 48 | | return maxLength; |
| 7 | 49 | | } |
| | 50 | | } |