Skip to content

1964. Find the Longest Valid Obstacle Course at Each Position 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 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
class Solution {
 public:
  // Similar to 300. Longest Increasing Subsequence
  vector<int> longestObstacleCourseAtEachPosition(vector<int>& obstacles) {
    vector<int> ans;
    // tails[i] := the minimum tail of all the increasing subsequences having
    // length i + 1
    vector<int> tails;

    for (const int obstacle : obstacles)
      if (tails.empty() || obstacle >= tails.back()) {
        tails.push_back(obstacle);
        ans.push_back(tails.size());
      } else {
        const int index = firstGreater(tails, obstacle);
        tails[index] = obstacle;
        ans.push_back(index + 1);
      }

    return ans;
  }

 private:
  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
30
31
32
33
34
class Solution {
  // Similar to 300. Longest Increasing Subsequence
  public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {
    List<Integer> ans = new ArrayList<>();
    // tails[i] := the minimum tail of all the increasing subsequences with
    // length i + 1
    List<Integer> tails = new ArrayList<>();

    for (final int obstacle : obstacles)
      if (tails.isEmpty() || obstacle >= tails.get(tails.size() - 1)) {
        tails.add(obstacle);
        ans.add(tails.size());
      } else {
        final int index = firstGreater(tails, obstacle);
        tails.set(index, obstacle);
        ans.add(index + 1);
      }

    return ans.stream().mapToInt(Integer::intValue).toArray();
  }

  private int firstGreater(List<Integer> A, int target) {
    int l = 0;
    int r = A.size();
    while (l < r) {
      final int m = (l + r) / 2;
      if (A.get(m) > target)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  # Similar to 300. Longest Increasing Subsequence
  def longestObstacleCourseAtEachPosition(
      self, obstacles: list[int],
  ) -> list[int]:
    ans = []
    # tails[i] := the minimum tail of all the increasing subsequences having
    # length i + 1
    tails = []

    for obstacle in obstacles:
      if not tails or obstacle >= tails[-1]:
        tails.append(obstacle)
        ans.append(len(tails))
      else:
        index = bisect.bisect_right(tails, obstacle)
        tails[index] = obstacle
        ans.append(index + 1)

    return ans