using System;
class Program
{
// Initializing DP array
static int[,] DP = new int[1000, 1000];
// Recursive Function to find minimum operations
static int Rec(int i, int prev, int[] A, int M)
{
// If we reach at the end of array
if (i == A.Length)
return 0;
// If we have covered this value already
if (DP[i, prev] != -1)
return DP[i, prev];
// Taking the difference as steps
int minOperations = (prev - A[i] + M) % M + Rec(i + 1, prev, A, M);
// Check if prev number is smaller or equal
if (A[i] >= prev)
minOperations = Math.Min(Rec(i + 1, A[i], A, M), minOperations);
// Return and update steps
return DP[i, prev] = minOperations;
}
// Function to initialize DP array and iterate on it
static int MinOperations(int N, int M, int[] A)
{
// Fill all the values with -1
for (int i = 0; i < 1000; i++)
{
for (int j = 0; j < 1000; j++)
{
DP[i, j] = -1;
}
}
// Call Iterator function
return Rec(0, 0, A, M);
}
// Driver code
static void Main()
{
// Inputs
int N = 3;
int M = 2;
int[] A = { 4, 3, 2 };
// Function call
Console.WriteLine(MinOperations(N, M, A));
}
}
// This code is contributed by rambabuguphka