[CSES] Increasing Array

1 minute read

Increasing Array

Task:

You are given an array of $n$ integers. You want to modify the array so that it is increasing, i.e., every element is at least as large as the previous element.

On each move, you may increase the value of any element by one. What is the minimum number of moves required?

Input

The first input line contains an integer $n$: the size of the array.

Then, the second line contains $n$ integers $x_1,x_2,\ldots,x_n$: the contents of the array.

Output

Print the minimum number of moves.

Constraints

  • $1 \le n \le 2 \cdot 10^5$
  • $1 \le x_i \le 10^9$
Example

Input:
5
3 2 5 1 7


Output:
5

Solutions:

Intuition:
The staright idea, is to make sure that the current element is not less than the last one. In other words, If it is equal or greater than the last element, skip it. Otherwise, we increase it to the previous element's value.

Implementation:

 1n=int(input())
 2arr=[int(i) for i in input().strip().split()]
 3def repetitions(n,arr):
 4    res,last=0,arr[0]
 5    for i in range(1,len(arr)):
 6        if last>arr[i]:
 7            res+=(last-arr[i])
 8        else:
 9            last=arr[i]
10    return res
11print(repetitions(n,arr))
12 

Analysis:

Time complexity: O(N).

Space complexity: O(1).

Help me water it