




Sponsored
Sponsored
In this approach, we use a combination of dynamic programming and binary search to find the longest obstacle course at each position. We maintain a list which helps to track the longest increasing subsequence (LIS) up to the current index. For each obstacle, we find its position in the LIS using binary search (which keeps it sorted), updating the LIS while also determining the length of the LIS at each step.
Time Complexity: O(n log n), as each binary search operation runs in O(log n) and is performed n times. Space Complexity: O(n), storing the longest sequence lengths.
1from bisect import bisect_right
2
3def longestObstacleCourseAtEachPosition(obstacles):
4    lis = []
5    ans = []
6    for obstacle in obstacles:
7        pos = bisect_right(lis, obstacle)
8        ans.append(pos + 1)
9        if pos == len(lis):
10            lis.append(obstacle)
11        else:
12            lis[pos] = obstacle
13    return ans
14The Python solution utilizes the bisect_right function from the built-in bisect module, which performs a binary search to help determine positions. The lis list maintains the lengths, and for each obstacle, the list is updated by replacing or extending as necessary.
This approach uses a Fenwick Tree (or BIT) to keep track of the lengths of obstacle courses efficiently. As we iterate through the obstacles array, we update our Fenwick Tree with the longest course length ending at each obstacle using range queries.
Time Complexity: O(n log m), where m is the maximum obstacle height. Space Complexity: O(m).
1#include <vector>
2#include <algorithm>
3
4class FenwickTree {
5    std::vector<int> tree;
6    int size;
public:
    FenwickTree(int size) : size(size), tree(size + 1, 0) {}
    void update(int index, int value) {
        for (; index <= size; index += index & -index)
            tree[index] = std::max(tree[index], value);
    }
    int query(int index) const {
        int max_val = 0;
        for (; index > 0; index -= index & -index)
            max_val = std::max(max_val, tree[index]);
        return max_val;
    }
};
std::vector<int> longestObstacleCourseAtEachPosition(const std::vector<int>& obstacles) {
    int max_obstacle = *max_element(obstacles.begin(), obstacles.end());
    FenwickTree fenwick(max_obstacle);
    std::vector<int> result;
    for (auto obs : obstacles) {
        int cur_len = fenwick.query(obs) + 1;
        result.push_back(cur_len);
        fenwick.update(obs, cur_len);
    }
    return result;
}The C++ version leverages a Fenwick Tree class designed to handle maximum queries and updates efficiently, focused on maintaining the longest course lengths during iteration.