Skip to content

Commit e27da64

Browse files
Create Insert a Progression Explanation.txt
1 parent 98cb727 commit e27da64

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
Let the value of the original array be |A[1] - A[2]| + |A[2] - A[3]| + ... + |A[n - 1] - A[n]|
2+
3+
Let the smallest and largest element of the array be L and R respectively.
4+
5+
-----
6+
7+
Let us notice that if we have an integer x, A[i] < x < A[i + 1], we can place x in between A[i] and A[i + 1] with no change in the cost.
8+
9+
(A[i + 1] - x) + (x - A[i]) = A[i + 1] - A[i]
10+
11+
-----
12+
13+
We can place all integers in the range [L, R] within the array in such a way that it does not increase the cost.
14+
15+
Now, we only need to deal with the prefix [1, L - 1] and the suffix [R + 1, X]
16+
17+
There are 3 options for both of these
18+
19+
1. Before the first number
20+
2. After the last number
21+
3. In between two numbers.
22+
23+
Suppose we place 1, 2, 3, ... , L - 1 in between A[i - 1] and A[i + 1], let us count the total difference in cost
24+
25+
Old Cost = A[i] - A[i - 1]
26+
New Cost = A[i] - (L - 1) + (L - 1) - (L - 1) ... - 1 + (A[i - 1] - 1) = (A[i] - 1) + (A[i - 1] - 1)
27+
Difference = 2(A[i] - 1)
28+
29+
-----
30+
31+
32+
void solve()
33+
{
34+
int no_of_elements, extra;
35+
cin >> no_of_elements >> extra;
36+
37+
vector <long long> A(no_of_elements + 1);
38+
for(int i = 1; i <= no_of_elements; i++)
39+
{
40+
cin >> A[i];
41+
}
42+
43+
long long value = 0;
44+
long long minimum = A[1], maximum = A[1];
45+
for(int i = 2; i <= no_of_elements; i++)
46+
{
47+
minimum = min(minimum, A[i]);
48+
maximum = max(maximum, A[i]);
49+
50+
value += abs(A[i] - A[i - 1]);
51+
}
52+
53+
if(minimum > 1)
54+
{
55+
long long minimum_contribution = min(A[1] - 1, A[no_of_elements] - 1);
56+
57+
for(int i = 2; i <= no_of_elements; i++)
58+
{
59+
minimum_contribution = min(minimum_contribution, (A[i] - 1)*2);
60+
}
61+
62+
value += minimum_contribution;
63+
}
64+
65+
if(maximum < extra)
66+
{
67+
long long maximum_contribution = min(extra - A[1], extra - A[no_of_elements]);
68+
69+
for(int i = 2; i <= no_of_elements; i++)
70+
{
71+
maximum_contribution = min(maximum_contribution, (extra - A[i])*2);
72+
}
73+
74+
value += maximum_contribution;
75+
}
76+
77+
cout << value << "\n";
78+
}

0 commit comments

Comments
 (0)