Krishnatejaswi S

Increasing Array

· Krishnatejaswi S

Link to the problem : Increasing Array

Intuition

The idea is to make an array increasing by making the current element equal to or greater than the previous element. and in each step we can increase the value of a single element by 1.

That means for ith element which is less than the i-1th element, we need elem[i-1] - elem[i] steps to make it equal to or greater than the i-1th element.

So we can come up with the following algorithm:

At the end of the loop, we will have the minimum number of steps to make the array increasing.

Solution

 1def main():
 2    n = int(input())
 3    nums = list(map(int, input().split()))
 4    count = 0
 5    for i in range(0,n-1):
 6        if nums[i] > nums[i+1]:
 7            count += nums[i] - nums[i+1]
 8            nums[i+1] = nums[i]
 9    print(count)
10
11if __name__ == "__main__":
12    main()

Mathematical Proof

Theorem: The greedy algorithm that ensures each element is at least as large as its predecessor gives the minimum total cost to make the array non-decreasing.

Proof by Induction:

Base Cases:

Inductive Hypothesis: Assume the greedy algorithm is optimal for arrays of size ≤ k.

Inductive Step: Consider an array of size k+1. Let the array be a[0], a[1], ..., a[k].

Apply the greedy algorithm:

  1. Process the first k elements optimally (by inductive hypothesis)
  2. For the last element a[k], if a[k-1] ≤ a[k], no change needed (cost 0)
  3. If a[k-1] > a[k], increment a[k] to a[k-1], costing a[k-1] - a[k]

Why this is optimal: Any optimal solution must satisfy a'[i] ≥ a'[i-1] for all i, where a' is the final array.

For the prefix a'[0] ... a'[k-1], the inductive hypothesis says our greedy choices give the minimum cost.

For the last pair a'[k-1] and a'[k]:

Key insight: The greedy choice doesn’t affect the optimality of the prefix because:

  1. The prefix constraints are already satisfied optimally
  2. Setting a[k] = max(a[k], a[k-1]) only affects the relationship between a[k-1] and a[k]
  3. This choice is independent of future elements since there are none

Proof by Contradiction : Suppose there exists an optimal solution with lower total cost than the greedy algorithm. Let the greedy algorithm produce array g with cost C_g. Let the optimal solution produce array o with cost C_o < C_g.

Since both g and o must satisfy g[i] ≥ g[i-1] and o[i] ≥ o[i-1] for all i:

Therefore, the greedy algorithm is optimal.

#competitive-programming #cses #algorithms #greedy

Reply to this post by email ↪