Minimum Operations to Make the Array K-Increasing — LeetCode 2111 Python Solution

HardArrayBinary Search
Problem
#2111
Reading time
3 min

The problem

You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k. The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1.

Example

Input
arr = [5,4,3,2,1], k = 1
Output
4
Explanation
For k = 1, the resultant array has to be non-decreasing.

Python solution

Python
class Solution:
    def kIncreasing(self, arr: List[int], k: int) -> int:
        def lis(arr):
            t = []
            for x in arr:
                idx = bisect_right(t, x)
                if idx == len(t):
                    t.append(x)
                else:
                    t[idx] = x
            return len(arr) - len(t)

        return sum(lis(arr[i::k]) for i in range(k))

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2111. Minimum Operations to Make the Array K-Increasing is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2111. Minimum Operations to Make the Array K-Increasing?
LeetCode 2111. Minimum Operations to Make the Array K-Increasing is rated Hard on LeetCode.
What topics does LeetCode 2111. Minimum Operations to Make the Array K-Increasing cover?
LeetCode 2111. Minimum Operations to Make the Array K-Increasing is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview