LeetCode Entry
1855. Maximum Distance Between a Pair of Values
Max distance a[i] not greater than b[j] window
1855. Maximum Distance Between a Pair of Values medium

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1333
Problem TLDR
Max distance a[i] not greater than b[j] #medium #sliding_window
Intuition
- Sliding window: for each left pointer move the rigth as far as possible
- Max-window: always expand the window, shrink window only when condition is broken
Approach
- the max-window is more clever
- binary search would also work
Complexity
-
Time complexity: \(O(n)\), nlog(n) for binarysearch
-
Space complexity: \(O(1)\)
Code
// 81ms
fun maxDistance(a: IntArray, b: IntArray) = maxOf(0, a.indices
.maxOf { i -> -b.asList().binarySearch { if (it < a[i]) 1 else -1 }-i-2 })
// 3ms
pub fn max_distance(a: Vec<i32>, b: Vec<i32>) -> i32 {
let (mut i, mut j) = (0, 0);
while i < a.len() && j < b.len() { if a[i] > b[j] { i += 1 }; j += 1}
0.max(j as i32 - i as i32 - 1)
}