| | 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.ShortestSubarrayWithSumAtLeastK; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ShortestSubarrayWithSumAtLeastKLinkedList : IShortestSubarrayWithSumAtLeastK |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int ShortestSubarray(int[] nums, int k) |
| 5 | 25 | | { |
| 5 | 26 | | var prefixSum = new long[nums.Length + 1]; |
| | 27 | |
|
| 42 | 28 | | for (var i = 0; i < nums.Length; i++) |
| 16 | 29 | | { |
| 16 | 30 | | prefixSum[i + 1] = prefixSum[i] + nums[i]; |
| 16 | 31 | | } |
| | 32 | |
|
| 5 | 33 | | var linkedList = new LinkedList<int>(); |
| | 34 | |
|
| 5 | 35 | | var minLength = nums.Length + 1; |
| | 36 | |
|
| 52 | 37 | | for (var i = 0; i < prefixSum.Length; i++) |
| 21 | 38 | | { |
| 26 | 39 | | while (linkedList.First is not null && prefixSum[i] - prefixSum[linkedList.First.Value] >= k) |
| 5 | 40 | | { |
| 5 | 41 | | minLength = Math.Min(minLength, i - linkedList.First.Value); |
| | 42 | |
|
| 5 | 43 | | linkedList.RemoveFirst(); |
| 5 | 44 | | } |
| | 45 | |
|
| 27 | 46 | | while (linkedList.Last is not null && prefixSum[i] <= prefixSum[linkedList.Last.Value]) |
| 6 | 47 | | { |
| 6 | 48 | | linkedList.RemoveLast(); |
| 6 | 49 | | } |
| | 50 | |
|
| 21 | 51 | | linkedList.AddLast(i); |
| 21 | 52 | | } |
| | 53 | |
|
| 5 | 54 | | return minLength <= nums.Length ? minLength : -1; |
| 5 | 55 | | } |
| | 56 | | } |