|
@@ -0,0 +1,55 @@
|
|
|
+struct Solution;
|
|
|
+impl Solution {
|
|
|
+ pub fn maximum_gap(nums: Vec<i32>) -> i32 {
|
|
|
+ let max = nums.iter().max().unwrap();
|
|
|
+ let min = nums.iter().min().unwrap();
|
|
|
+ if max == min { return 0; }
|
|
|
+ let n = nums.len();
|
|
|
+
|
|
|
+ let mut gap = (max - min) / (n as i32 -1);
|
|
|
+ if (max - min) % (n as i32 -1) != 0 {
|
|
|
+ gap += 1;
|
|
|
+ }
|
|
|
+ let mut min_bucket = vec![i32::MAX; n];
|
|
|
+ let mut max_bucket = vec![i32::MIN; n];
|
|
|
+ for i in 0..n {
|
|
|
+ let idx = ((nums[i] - min) / gap) as usize;
|
|
|
+ min_bucket[idx] = min_bucket[idx].min(nums[i]);
|
|
|
+ max_bucket[idx] = max_bucket[idx].max(nums[i]);
|
|
|
+ }
|
|
|
+
|
|
|
+ // println!("max_bucket: {:?}", max_bucket);
|
|
|
+ // println!("min_bucket: {:?}", min_bucket);
|
|
|
+
|
|
|
+ let mut res = i32::MIN;
|
|
|
+ let mut prev_max = i32::MIN;
|
|
|
+ for i in 0..n {
|
|
|
+ if min_bucket[i] == i32::MAX {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ if prev_max == i32::MIN {
|
|
|
+ prev_max = max_bucket[i];
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ res = res.max(min_bucket[i] - prev_max);
|
|
|
+ prev_max = max_bucket[i];
|
|
|
+ }
|
|
|
+ res
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+#[cfg(test)]
|
|
|
+mod tests {
|
|
|
+ use super::*;
|
|
|
+
|
|
|
+ #[test]
|
|
|
+ fn test_maximum_gap() {
|
|
|
+ let nums = vec![3,6,9,1,10];
|
|
|
+ let res = Solution::maximum_gap(nums);
|
|
|
+ assert_eq!(res, 3);
|
|
|
+ }
|
|
|
+}
|