Skip to content

Commit 03ccac3

Browse files
committed
LC 2461. Maximum Sum of Distinct Subarrays With Length K (Rust)
1 parent 8db6d12 commit 03ccac3

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,7 @@ to the solution in this repository.
718718
| [2441. Largest Positive Integer That Exists With Its Negative][lc2441] | 🟢 Easy | [![rust](res/rs.png)][lc2441rs] |
719719
| [2444. Count Subarrays With Fixed Bounds][lc2444] | 🔴 Hard | [![python](res/py.png)][lc2444py] [![rust](res/rs.png)][lc2444rs] |
720720
| [2448. Minimum Cost to Make Array Equal][lc2448] | 🔴 Hard | [![rust](res/rs.png)][lc2448rs] |
721+
| [2461. Maximum Sum of Distinct Subarrays With Length K][lc2461] | 🟠 Medium | [![rust](res/rs.png)][lc2461rs] |
721722
| [2462. Total Cost to Hire K Workers][lc2462] | 🟠 Medium | [![python](res/py.png)][lc2462py] |
722723
| [2463. Minimum Total Distance Traveled][lc2463] | 🔴 Hard | [![rust](res/rs.png)][lc2463rs] |
723724
| [2466. Count Ways To Build Good Strings][lc2466] | 🟠 Medium | [![rust](res/rs.png)][lc2466rs] |
@@ -2375,6 +2376,8 @@ to the solution in this repository.
23752376
[lc2444rs]: leetcode/count-subarrays-with-fixed-bounds.rs
23762377
[lc2448]: https://leetcode.com/problems/minimum-cost-to-make-array-equal/
23772378
[lc2448rs]: leetcode/minimum-cost-to-make-array-equal.rs
2379+
[lc2461]: https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/
2380+
[lc2461rs]: leetcode/maximum-sum-of-distinct-subarrays-with-length-k.rs
23782381
[lc2462]: https://leetcode.com/problems/total-cost-to-hire-k-workers/
23792382
[lc2462py]: leetcode/total-cost-to-hire-k-workers.py
23802383
[lc2463]: https://leetcode.com/problems/minimum-total-distance-traveled/
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// 2461. Maximum Sum of Distinct Subarrays With Length K
2+
// 🟠 Medium
3+
//
4+
// https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/
5+
//
6+
// Tags: Array - Hash Table - Sliding Window
7+
8+
use std::collections::HashMap;
9+
10+
struct Solution;
11+
impl Solution {
12+
/// Use a sliding window of size k, keep its sum and the count of elements in the window, also
13+
/// the number of duplicates, add values from the right and pop them from the left updating the
14+
/// counts, sum and duplicates, if the current window does not have duplicates, max its value
15+
/// with the result.
16+
///
17+
/// Time complexity: O(n) - We process each element in the input in O(1~)
18+
/// Space complexity: O(n) - The counts hashmap could have one entry per value in the input
19+
/// vector.
20+
///
21+
/// Runtime 32 ms Beats 5%
22+
/// Memory 7.11 MB Beats 9%
23+
pub fn maximum_subarray_sum(nums: Vec<i32>, k: i32) -> i64 {
24+
let mut counts = HashMap::<i32, usize>::new();
25+
let mut duplicates = 0;
26+
let k = k as usize;
27+
let n = nums.len();
28+
let mut current_sum = 0i64;
29+
let mut res = 0i64;
30+
for &num in &nums[..k] {
31+
current_sum += num as i64;
32+
counts.entry(num).and_modify(|c| *c += 1).or_insert(1);
33+
if counts[&num] == 2 {
34+
duplicates += 1;
35+
}
36+
}
37+
if duplicates == 0 {
38+
res = current_sum;
39+
}
40+
let mut l = 0;
41+
for r in k..n {
42+
current_sum += nums[r] as i64;
43+
counts.entry(nums[r]).and_modify(|c| *c += 1).or_insert(1);
44+
if counts[&nums[r]] == 2 {
45+
duplicates += 1;
46+
}
47+
current_sum -= nums[l] as i64;
48+
counts.entry(nums[l]).and_modify(|c| *c -= 1);
49+
if counts[&nums[l]] == 1 {
50+
duplicates -= 1;
51+
}
52+
if duplicates == 0 {
53+
res = res.max(current_sum);
54+
}
55+
l += 1;
56+
}
57+
res
58+
}
59+
}
60+
61+
// Tests.
62+
fn main() {
63+
let tests = [(vec![1, 5, 4, 2, 9, 9, 9], 3, 15), (vec![4, 4, 4], 3, 0)];
64+
println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len());
65+
let mut success = 0;
66+
for (i, t) in tests.iter().enumerate() {
67+
let res = Solution::maximum_subarray_sum(t.0.clone(), t.1);
68+
if res == t.2 {
69+
success += 1;
70+
println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i);
71+
} else {
72+
println!(
73+
"\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {:?}!!\x1b[0m",
74+
i, t.2, res
75+
);
76+
}
77+
}
78+
println!();
79+
if success == tests.len() {
80+
println!("\x1b[30;42m✔ All tests passed!\x1b[0m")
81+
} else if success == 0 {
82+
println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m")
83+
} else {
84+
println!(
85+
"\x1b[31mx\x1b[95m {} tests failed!\x1b[0m",
86+
tests.len() - success
87+
)
88+
}
89+
}

0 commit comments

Comments
 (0)