/**
* Problem: LeetCode 3414 - Maximum Score of Non-overlapping Intervals
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
import java.util.*;
/**
* Problem: LeetCode 3414 - Maximum Score of Non-overlapping Intervals
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int[] maximumWeight(List<List<Integer>> intervals) {
int n = intervals.size();
// arr: [l, r, weight, originalIndex]
int[][] arr = new int[n][4];
for (int i = 0; i < n; i++) {
arr[i][0] = intervals.get(i).get(0);
arr[i][1] = intervals.get(i).get(1);
arr[i][2] = intervals.get(i).get(2);
arr[i][3] = i;
}
Arrays.sort(arr, (a, b) -> a[1] != b[1] ? Integer.compare(a[1], b[1]) :
a[0] != b[0] ? Integer.compare(a[0], b[0]) :
a[2] != b[2] ? Integer.compare(a[2], b[2]) :
Integer.compare(a[3], b[3]));
// posScore[i + 1][k]: best total weight using k non-overlapping intervals from first i intervals
// posIdx[i + 1][k]: lexicographically smallest sorted indices achieving posScore
long[][] posScore = new long[n + 1][5];
int[][][] posIdx = new int[n + 1][5][];
for (long[] row : posScore) {
Arrays.fill(row, -1);
}
for (int i = 0; i < n; i++) {
// Binary search: rightmost j < i where arr[j][1] < arr[i][0]
int lo = 0, hi = i - 1, prev = -1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid][1] < arr[i][0]) {
prev = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
int p = prev + 1; // 1-based prefix index
for (int k = 1; k <= 4; k++) {
// Option 1: Do not pick interval i
posScore[i + 1][k] = posScore[i][k];
posIdx[i + 1][k] = posIdx[i][k];
// Option 2: Pick interval i with best (k-1) from prefix p
long prevS = (k == 1) ? 0 : posScore[p][k - 1];
int[] prevI = (k == 1) ? new int[0] : posIdx[p][k - 1];
if (k == 1 || prevS >= 0) {
long newScore = prevS + arr[i][2];
int[] newIdx = append(prevI, arr[i][3]);
Arrays.sort(newIdx);
if (posScore[i + 1][k] < newScore ||
(posScore[i + 1][k] == newScore && isLess(newIdx, posIdx[i + 1][k]))) {
posScore[i + 1][k] = newScore;
posIdx[i + 1][k] = newIdx;
}
}
}
}
long best = -1;
int[] ans = null;
for (int k = 1; k <= 4; k++) {
long s = posScore[n][k];
int[] idx = posIdx[n][k];
if (s < 0) continue;
if (s > best || (s == best && isLess(idx, ans))) {
best = s;
ans = idx;
}
}
return ans == null ? new int[0] : ans;
}
private int[] append(int[] arr, int val) {
int[] res = new int[arr.length + 1];
System.arraycopy(arr, 0, res, 0, arr.length);
res[arr.length] = val;
return res;
}
private boolean isLess(int[] a, int[] b) {
if (b == null) return true;
if (a == null) return false;
for (int i = 0; i < Math.min(a.length, b.length); i++) {
if (a[i] != b[i]) return a[i] < b[i];
}
return a.length < b.length;
}
}
"""
Problem: LeetCode 3414 - Maximum Score of Non-overlapping Intervals
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
from typing import List
import bisect
class Solution:
def maximumWeight(self, intervals: List[List[int]]) -> List[int]:
n = len(intervals)
# Store intervals as (l, r, weight, originalIndex)
arr = [(intervals[i][0], intervals[i][1], intervals[i][2], i) for i in range(n)]
# Sort by right endpoint, then left, then weight, then original index
arr.sort(key=lambda x: (x[1], x[0], x[2], x[3]))
r_list = [x[1] for x in arr]
# pos_score[i][k] and pos_idx[i][k]
pos_score = [[-1] * 5 for _ in range(n + 1)]
pos_idx = [[None] * 5 for _ in range(n + 1)]
def is_less(a, b):
if b is None:
return True
if a is None:
return False
return a < b
for i in range(n):
l, r, w, orig_idx = arr[i]
# Find number of non-overlapping intervals strictly before current interval's start
p = bisect.bisect_left(r_list, l, 0, i)
for k in range(1, 5):
# Option 1: Do not pick interval i
pos_score[i + 1][k] = pos_score[i][k]
pos_idx[i + 1][k] = pos_idx[i][k]
# Option 2: Pick interval i
prev_s = 0 if k == 1 else pos_score[p][k - 1]
prev_i = [] if k == 1 else pos_idx[p][k - 1]
if k == 1 or prev_s >= 0:
new_score = prev_s + w
new_idx = sorted(prev_i + [orig_idx])
if pos_score[i + 1][k] < new_score or (
pos_score[i + 1][k] == new_score and is_less(new_idx, pos_idx[i + 1][k])
):
pos_score[i + 1][k] = new_score
pos_idx[i + 1][k] = new_idx
best_score = -1
ans = []
for k in range(1, 5):
s = pos_score[n][k]
idx = pos_idx[n][k]
if s < 0:
continue
if s > best_score or (s == best_score and is_less(idx, ans)):
best_score = s
ans = idx
return ans if ans is not None else []
/**
* Problem: LeetCode 3414 - Maximum Score of Non-overlapping Intervals
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <algorithm>
/**
* Problem: LeetCode 3414 - Maximum Score of Non-overlapping Intervals
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
struct Interval {
int l, r, w, id;
};
bool isLess(const std::vector<int>& a, const std::vector<int>& b) {
if (b.empty()) return true;
if (a.empty()) return false;
return a < b;
}
public:
std::vector<int> maximumWeight(std::vector<std::vector<int>>& intervals) {
int n = intervals.size();
std::vector<Interval> arr(n);
for (int i = 0; i < n; i++) {
arr[i] = {intervals[i][0], intervals[i][1], intervals[i][2], i};
}
std::sort(arr.begin(), arr.end(), [](const Interval& a, const Interval& b) {
if (a.r != b.r) return a.r < b.r;
if (a.l != b.l) return a.l < b.l;
if (a.w != b.w) return a.w < b.w;
return a.id < b.id;
});
std::vector<int> r_list(n);
for (int i = 0; i < n; i++) {
r_list[i] = arr[i].r;
}
// posScore[i + 1][k]: best weight using k intervals from first i
std::vector<std::vector<long long>> posScore(n + 1, std::vector<long long>(5, -1));
std::vector<std::vector<std::vector<int>>> posIdx(n + 1, std::vector<std::vector<int>>(5));
for (int i = 0; i < n; i++) {
// Find rightmost j < i where arr[j].r < arr[i].l
int p = std::lower_bound(r_list.begin(), r_list.begin() + i, arr[i].l) - r_list.begin();
for (int k = 1; k <= 4; k++) {
// Option 1: Do not pick interval i
posScore[i + 1][k] = posScore[i][k];
posIdx[i + 1][k] = posIdx[i][k];
// Option 2: Pick interval i
long long prevS = (k == 1) ? 0 : posScore[p][k - 1];
if (k == 1 || prevS >= 0) {
long long newScore = prevS + arr[i].w;
std::vector<int> newIdx;
if (k > 1) {
newIdx = posIdx[p][k - 1];
}
newIdx.push_back(arr[i].id);
std::sort(newIdx.begin(), newIdx.end());
if (posScore[i + 1][k] < newScore ||
(posScore[i + 1][k] == newScore && (posIdx[i + 1][k].empty() || newIdx < posIdx[i + 1][k]))) {
posScore[i + 1][k] = newScore;
posIdx[i + 1][k] = newIdx;
}
}
}
}
long long best = -1;
std::vector<int> ans;
for (int k = 1; k <= 4; k++) {
long long s = posScore[n][k];
if (s < 0) continue;
if (s > best || (s == best && (ans.empty() || posIdx[n][k] < ans))) {
best = s;
ans = posIdx[n][k];
}
}
return ans;
}
};
/**
* Problem: LeetCode 3414 - Maximum Score of Non-overlapping Intervals
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var maximumWeight = function(intervals) {
const n = intervals.length;
const arr = new Array(n);
for (let i = 0; i < n; i++) {
arr[i] = [intervals[i][0], intervals[i][1], intervals[i][2], i];
}
arr.sort((a, b) => {
if (a[1] !== b[1]) return a[1] - b[1];
if (a[0] !== b[0]) return a[0] - b[0];
if (a[2] !== b[2]) return a[2] - b[2];
return a[3] - b[3];
});
const posScore = Array.from({ length: n + 1 }, () => new Array(5).fill(-1n));
const posIdx = Array.from({ length: n + 1 }, () => new Array(5).fill(null));
function isLess(a, b) {
if (!b) return true;
if (!a) return false;
const len = Math.min(a.length, b.length);
for (let i = 0; i < len; i++) {
if (a[i] !== b[i]) return a[i] < b[i];
}
return a.length < b.length;
}
for (let i = 0; i < n; i++) {
let lo = 0, hi = i - 1, prev = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (arr[mid][1] < arr[i][0]) {
prev = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
const p = prev + 1;
for (let k = 1; k <= 4; k++) {
posScore[i + 1][k] = posScore[i][k];
posIdx[i + 1][k] = posIdx[i][k];
const prevS = (k === 1) ? 0n : posScore[p][k - 1];
const prevI = (k === 1) ? [] : posIdx[p][k - 1];
if (k === 1 || prevS >= 0n) {
const newScore = prevS + BigInt(arr[i][2]);
const newIdx = (prevI ? [...prevI] : []);
newIdx.push(arr[i][3]);
newIdx.sort((a, b) => a - b);
if (posScore[i + 1][k] < newScore ||
(posScore[i + 1][k] === newScore && isLess(newIdx, posIdx[i + 1][k]))) {
posScore[i + 1][k] = newScore;
posIdx[i + 1][k] = newIdx;
}
}
}
}
let best = -1n;
let ans = [];
for (let k = 1; k <= 4; k++) {
const s = posScore[n][k];
const idx = posIdx[n][k];
if (s < 0n) continue;
if (s > best || (s === best && isLess(idx, ans))) {
best = s;
ans = idx;
}
}
return ans || [];
};