




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.
1import java.util.*;
2
3public class LongestObstacleCourse {
4    public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {
5        int n = obstacles.length;
6        List<Integer> lis = new ArrayList<>();
7        int[] ans = new int[n];
8        for (int i = 0; i < n; i++) {
9            int obstacle = obstacles[i];
10            int pos = Collections.binarySearch(lis, obstacle);
11            if (pos < 0) pos = -(pos + 1);
12            ans[i] = pos + 1;
13            if (pos == lis.size()) {
14                lis.add(obstacle);
15            } else {
16                lis.set(pos, obstacle);
17            }
18        }
19        return ans;
20    }
21}
22The Java solution manages a list to keep track of the increasing sequence. Collections.binarySearch() helps to find the right position and modifies the current list 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).
1class FenwickTree:
2    def __init__(self,    
            
This Python code defines a Fenwick Tree class to support efficient updates and queries. The main function iterates over the obstacles, with each step updating and querying the Fenwick Tree for the current obstacle height, ensuring optimal performance.