| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.MakeSumDivisibleByP; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class MakeSumDivisibleByPPrefixSum : IMakeSumDivisibleByP |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <param name="p"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public int MinSubarray(int[] nums, int p) |
| | 3 | 25 | | { |
| | 14 | 26 | | var sum = nums.Aggregate<int, long>(0, (current, num) => current + num); |
| | | 27 | | |
| | 3 | 28 | | var target = (int)(sum % p); |
| | | 29 | | |
| | 3 | 30 | | if (target == 0) |
| | 1 | 31 | | { |
| | 1 | 32 | | return 0; |
| | | 33 | | } |
| | | 34 | | |
| | 2 | 35 | | var prefixModDictionary = new Dictionary<int, int> { [0] = -1 }; |
| | | 36 | | |
| | 2 | 37 | | var result = nums.Length; |
| | 2 | 38 | | var currentMod = 0; |
| | | 39 | | |
| | 20 | 40 | | for (var i = 0; i < nums.Length; i++) |
| | 8 | 41 | | { |
| | 8 | 42 | | currentMod = (currentMod + nums[i]) % p; |
| | | 43 | | |
| | 8 | 44 | | var complement = (currentMod - target + p) % p; |
| | | 45 | | |
| | 8 | 46 | | if (prefixModDictionary.TryGetValue(complement, out var value)) |
| | 4 | 47 | | { |
| | 4 | 48 | | result = Math.Min(result, i - value); |
| | 4 | 49 | | } |
| | | 50 | | |
| | 8 | 51 | | prefixModDictionary[currentMod] = i; |
| | 8 | 52 | | } |
| | | 53 | | |
| | 2 | 54 | | return result == nums.Length ? -1 : result; |
| | 3 | 55 | | } |
| | | 56 | | } |