Sequence Transformation
InterviewTime limit2sMemory limit512 MB
Given a sequence of non-negative integers, find the minimum number of single increments needed so that 1,2,...,h appear consecutively as a block, or report that it is impossible.
- Level
Medium6 of 10
- Topics
- Array, Sliding window, Prefix sum, Greedy
- Solved
- No attempts yet
Problem
The math teacher dislikes Kolya very much and always makes him answer at the blackboard with the hardest problems.
Today she wrote a sequence of non-negative integers on the blackboard and called Kolya up. In one action, the teacher allows Kolya to erase any number and write in its place a number one greater. The teacher demands that Kolya, in the minimum number of actions, make the numbers 1 through appear consecutively somewhere in this sequence.
Help Kolya find the minimum number of actions needed so that for some , , , ..., , or determine that this is impossible and the teacher is again bullying poor Kolya with impunity.
Input
The first line of the input file contains two positive integers: and (). The second line contains numbers , the initial values of the sequence ().
Output
In a single line of the output file, print the minimum number of actions with which Kolya can complete the task, or if it is impossible.
Hint
In the first example, Kolya must increase the third number by 1 twice and the fourth number once. Then the sequence becomes 1, 1, 2, 3, and for the required condition holds.
In the second example, it is impossible to obtain 1 and 2 consecutively in the sequence.