-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
55 lines (48 loc) · 1.56 KB
/
Copy pathProgram.cs
File metadata and controls
55 lines (48 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.Linq;
namespace ShortestSubarray
{
class Program
{
static void Main(string[] args)
{
var solution = new Solution();
var res = solution.ShortestSubarray(new[] { 1, -1, 1, -1, 1, 2, 2, -1, 1, -1, 1, 4, -1, 1 }, 5);
Console.WriteLine(res);
}
}
public class Solution
{
public int ShortestSubarray(int[] A, int K)
{
var n = A.Length;
var sum = new long[n + 1];
for (var i = 0; i < n; i++)
{
sum[i + 1] = sum[i] + A[i];
Console.Write($"{i + 1}:{sum[i] + A[i]}; ");
}
Console.WriteLine();
var minSub = n + 1;
var range = new LinkedList<int>();
for (var y = 0; y < sum.Length; y++)
{
// extending range if sum is not growing
while (range.Count > 0 && sum[y] <= sum[range.Last.Value])
{
range.RemoveLast();
}
// move the start forward if current sum is GE the condition
while (range.Count > 0 && sum[y] >= sum[range.First.Value] + K)
{
minSub = Math.Min(minSub, y - range.First.Value);
range.RemoveFirst();
}
range.AddLast(y);
Console.WriteLine(string.Join(",", range));
}
return minSub < n + 1 ? minSub : -1;
}
}
}