begin
i:=1;j:=1;
sum := A[1]
min:=n; finish:=false;
while not finish do
if sum < M then
if j=n then finish:=true
else
begin
j:=j+1;
sum:= sum + A[j]
end
else
begin
if(j-i) < min then min:=j-i;
sum:=sum – A[i];
i:=i+1;
end
writeln (min +1);
end.
Algorithm
'i' indicates the starting marker and 'j' acts as ending marker for the sum sequence. 'sum' is initialised as the first element in the array because the algorithm proceeds by taking the sum of remaining elements. 'finish' is a boolean variable that indicates exit from the loop.
After entering the loop for the first time with '$finish$' as false, the sum is checked if it's strictly less than "$M$". If that's the case j is incremented and the sum is modified to sum $+ A[j]$. When 'sum' becomes greater than or equal to '$M$', '$min$' is modified to the latest number of elements that make the sum greater than or equal to '$M$' and then, the first element is stripped off from the sum and '$i$' is incremented by one to move the initial marker of the sum sequence. The loop runs till '$j$' reaches the end of the array.
The algorithm keeps track of '$min$' i.e. the number of elements in the minimum sum sequence. This is very similar to the way we find the minimum value in an array by modifying the min value whenever a lesser value is encountered.