Your algorithm is incorrect. You basically only check middle of the sequence, which doesn’t make any sense. Instead you should start with both indexes at the beginning of the array and increment right as long as sum of subrange is smaller than K. When it gets bigger start incrementing left until it is smaller again. Now you have a candidate for your shortest subsequence – save it. Repeat until right won’t get past the end of array, updating your candidate if new one is shorter.
4
solved Find minimal length of sub-array whose sum is greater than K [closed]