Skip to content

2111. Minimum Operations to Make the Array K-Increasing 👍

  • Time: $O(n\log(n / k))$
  • Space: $O(n / k)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  int kIncreasing(vector<int>& arr, int k) {
    int ans = 0;

    for (int i = 0; i < k; ++i) {
      vector<int> A;
      for (int j = i; j < arr.size(); j += k)
        A.push_back(arr[j]);
      ans += numReplaced(A);
    }

    return ans;
  }

 private:
  int numReplaced(const vector<int>& A) {
    vector<int> tails;
    for (const int a : A)
      if (tails.empty() || tails.back() <= a)
        tails.push_back(a);
      else
        tails[firstGreater(tails, a)] = a;
    return A.size() - tails.size();
  }

  int firstGreater(const vector<int>& A, int target) {
    return ranges::upper_bound(A, target) - A.begin();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
  public int kIncreasing(int[] arr, int k) {
    int ans = 0;

    for (int i = 0; i < k; ++i) {
      List<Integer> A = new ArrayList<>();
      for (int j = i; j < arr.length; j += k)
        A.add(arr[j]);
      ans += numReplaced(A);
    }

    return ans;
  }

  private int numReplaced(List<Integer> A) {
    List<Integer> tails = new ArrayList<>();
    for (final int a : A)
      if (tails.isEmpty() || tails.get(tails.size() - 1) <= a)
        tails.add(a);
      else
        tails.set(firstGreater(tails, a), a);
    return A.size() - tails.size();
  }

  private int firstGreater(List<Integer> A, int target) {
    final int i = Collections.binarySearch(A, target + 1);
    return i < 0 ? -i - 1 : i;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def kIncreasing(self, arr: list[int], k: int) -> int:
    def numReplaced(A: list[int]) -> int:
      tails = []
      for a in A:
        if not tails or tails[-1] <= a:
          tails.append(a)
        else:
          tails[bisect_right(tails, a)] = a
      return len(A) - len(tails)

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