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> tail;
    for (const int a : A)
      if (tail.empty() || tail.back() <= a)
        tail.push_back(a);
      else
        tail[firstGreater(tail, a)] = a;
    return A.size() - tail.size();
  }

  int firstGreater(const vector<int>& tail, int target) {
    return upper_bound(begin(tail), end(tail), target) - begin(tail);
  }
};
 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
31
32
33
34
35
36
37
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> tail = new ArrayList<>();
    for (final int a : A)
      if (tail.isEmpty() || tail.get(tail.size() - 1) <= a)
        tail.add(a);
      else
        tail.set(firstGreater(tail, a), a);
    return A.size() - tail.size();
  }

  private int firstGreater(List<Integer> tail, int target) {
    int l = 0;
    int r = tail.size();
    while (l < r) {
      final int m = (l + r) / 2;
      if (tail.get(m) > target)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
}
 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:
      tail = []
      for a in A:
        if not tail or tail[-1] <= a:
          tail.append(a)
        else:
          tail[bisect_right(tail, a)] = a
      return len(A) - len(tail)

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