Skip to content

Commit b15b9c3

Browse files
Add files via upload
1 parent b699e74 commit b15b9c3

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
We can binary search the number of operations required to make the array non-decreasing.
2+
3+
We can make A[i] = (A[i], A[i] + x) (mod M).
4+
5+
These are the reachable values for A[i].
6+
7+
We will choose the smallest value possible at each step for each A[i], while maintaining the condition that A[i] is not smaller than the prefix minimum.
8+
9+
If possible we will make A[i] = the prefix minimum. Otherwise, we will make the minimum = A[i].
10+
11+
If A[i] can't be made >= minimum and is < minimum, then it is not possible in x moves.
12+
13+
---
14+
15+
At each step, we are making the minimum as small as possible. It is never optimal to increase some previous element by more than what we have as that would increase the minimum.
16+
17+
---
18+
19+
int possible(int operations, int m, vector <int> &A)
20+
{
21+
int minimum = 0;
22+
23+
for(int i = 1; i < A.size(); i++)
24+
{
25+
if( (A[i] <= minimum && A[i] + operations >= minimum) || (A[i] > minimum && A[i] + operations - m >= minimum) )
26+
continue;
27+
28+
if(A[i] < minimum)
29+
return false;
30+
31+
minimum = A[i];
32+
}
33+
34+
return true;
35+
}
36+
37+
int main()
38+
{
39+
int no_of_elements, m;
40+
cin >> no_of_elements >> m;
41+
42+
vector <int> A(no_of_elements + 1);
43+
for(int i = 1; i <= no_of_elements; i++)
44+
cin >> A[i];
45+
46+
int left = -1, right = m;
47+
while(right - left > 1)
48+
{
49+
int mid = (left + right)/2;
50+
51+
if(possible(mid, m, A))
52+
right = mid;
53+
else
54+
left = mid;
55+
}
56+
57+
cout << right;
58+
return 0;
59+
}

0 commit comments

Comments
 (0)