-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmaximum-element-after-decreasing-and-rearranging.rs
88 lines (84 loc) · 2.78 KB
/
maximum-element-after-decreasing-and-rearranging.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// 1846. Maximum Element After Decreasing and Rearranging
// 🟠 Medium
//
// https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/
//
// Tags: Array - Greedy - Sorting
struct Solution;
impl Solution {
/// Sort the input, then iterate through the elements, the maximum at each position will be the
/// minimum between its value and the value computed for (arr[i-1] + 1) because we can, at
/// most, increase the values by one each position.
///
/// Time complexity: O(n*log(n)) - We are sorting the input.
/// Space complexity: O(n) - The local copy.
///
/// Runtime 5 ms Beats 33.33%
/// Memory 3.84 MB Beats 33.33%
pub fn maximum_element_after_decrementing_and_rearranging(arr: Vec<i32>) -> i32 {
let mut arr = arr;
arr.sort_unstable();
arr.into_iter().fold(0, |acc, x| x.min(acc + 1))
}
/// Similar solution, but use counting sort.
///
/// Time complexity: O(n) - We iterate over the elements 2 times.
/// Space complexity: O(n) - The counting buckets.
///
/// Runtime 0 ms Beats 100%
/// Memory 4.17 MB Beats 33.33%
pub fn maximum_element_after_decrementing_and_rearranging_2(arr: Vec<i32>) -> i32 {
let n = arr.len();
let mut counts = vec![0; n + 1];
for num in arr {
counts[n.min(num as usize)] += 1;
}
let mut res = 1;
for i in 2..=n {
res = i.min(res + counts[i]);
}
res as i32
}
/// Similar solution, use counting sort, update the second loop to use an iterator.
///
/// Time complexity: O(n) - We iterate over the elements 2 times.
/// Space complexity: O(n) - The counting buckets.
///
/// Runtime 8 ms Beats 33.33%
/// Memory 3.88 MB Beats 33.33%
pub fn maximum_element_after_decrementing_and_rearranging_3(arr: Vec<i32>) -> i32 {
let n = arr.len();
let mut counts = vec![0; n + 1];
for num in arr {
counts[n.min(num as usize)] += 1;
}
counts
.into_iter()
.enumerate()
.skip(2)
.fold(1, |acc, (idx, val)| idx.min(acc + val)) as i32
}
}
// Tests.
fn main() {
let tests = [
(vec![2, 2, 1, 2, 1], 2),
(vec![100, 1, 1000], 3),
(vec![1, 2, 3, 4, 5], 5),
];
for t in tests {
assert_eq!(
Solution::maximum_element_after_decrementing_and_rearranging(t.0.clone()),
t.1
);
assert_eq!(
Solution::maximum_element_after_decrementing_and_rearranging_2(t.0.clone()),
t.1
);
assert_eq!(
Solution::maximum_element_after_decrementing_and_rearranging_3(t.0.clone()),
t.1
);
}
println!("\x1b[92m» All tests passed!\x1b[0m")
}