| | 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.MaximumDifferenceBetweenEvenAndOddFrequency1; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MaximumDifferenceBetweenEvenAndOddFrequency1FrequencyArray : |
| | 16 | | IMaximumDifferenceBetweenEvenAndOddFrequency1 |
| | 17 | | { |
| | 18 | | /// <summary> |
| | 19 | | /// Time complexity - O(n) |
| | 20 | | /// Space complexity - O(1) |
| | 21 | | /// </summary> |
| | 22 | | /// <param name="s"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int MaxDifference(string s) |
| 2 | 25 | | { |
| 2 | 26 | | var frequencyArray = new int['z' - 'a' + 1]; |
| | 27 | |
|
| 38 | 28 | | foreach (var c in s) |
| 16 | 29 | | { |
| 16 | 30 | | frequencyArray['z' - c]++; |
| 16 | 31 | | } |
| | 32 | |
|
| 2 | 33 | | var oddFrequency = int.MinValue; |
| 2 | 34 | | var evenFrequency = int.MaxValue; |
| | 35 | |
|
| 110 | 36 | | foreach (var frequency in frequencyArray) |
| 52 | 37 | | { |
| 52 | 38 | | if (frequency == 0) |
| 46 | 39 | | { |
| 46 | 40 | | continue; |
| | 41 | | } |
| | 42 | |
|
| 6 | 43 | | if (frequency % 2 == 0) |
| 2 | 44 | | { |
| 2 | 45 | | evenFrequency = Math.Min(evenFrequency, frequency); |
| 2 | 46 | | } |
| | 47 | | else |
| 4 | 48 | | { |
| 4 | 49 | | oddFrequency = Math.Max(oddFrequency, frequency); |
| 4 | 50 | | } |
| 6 | 51 | | } |
| | 52 | |
|
| 2 | 53 | | return oddFrequency - evenFrequency; |
| 2 | 54 | | } |
| | 55 | | } |