using System;
using System.Collections.Generic;
using System.Linq;
namespace MainProgram
{
class MainClass
{
public static int binary_search(SortedDictionary<int, List<int>> m, int value, int index)
{
KeyValuePair<int, List<int>> it = m.FirstOrDefault(x => x.Key >= value);
if (it.Equals(default(KeyValuePair<int, List<int>>)))
return 0;
List<int> list = it.Value;
int i = list.BinarySearch(index);
if (i >= 0)
return list[i];
return -i - 1 < list.Count ? list[-i - 1] : 0;
}
public static int findSubarray(int[] arr, int n, int k)
{
int[] pre_array = new int[n];
SortedDictionary<int, List<int>> m = new SortedDictionary<int, List<int>>();
pre_array[0] = arr[0];
List<int> l = new List<int>();
l.Add(0);
m.Add(pre_array[0], l);
if (arr[0] >= k)
return 1;
int ans = Int32.MaxValue;
for (int i = 1; i < n; i++)
{
pre_array[i]
= arr[i] + pre_array[i - 1];
if (pre_array[i] >= k)
ans = Math.Min(ans, i + 1);
KeyValuePair<int, List<int>> it = m.Last();
if (pre_array[i] >= it.Key)
{
if (m.ContainsKey(pre_array[i]))
{
m[pre_array[i]].Add(i);
}
else
{
m.Add(pre_array[i], new List<int> { i });
}
}
}
for (int i = 1; i < n; i++)
{
int temp
= binary_search(m,
pre_array[i - 1] + k,
i);
if (temp == 0)
continue;
ans = Math.Min(ans, temp - i + 1);
}
if (ans <= n)
return ans;
return -1;
}
public static void Main(string[] args)
{
int[] arr = { 2, 1, 1, -4, 3, 1, -1, 2 };
int k = 5;
int n = arr.Length;
Console.WriteLine(findSubarray(arr, n, k));
}
}
}