Skip to content

Commit 2bf31c4

Browse files
committed
Add problem 2501: Longest Square Streak in an Array
1 parent 3e961a3 commit 2bf31c4

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

Diff for: src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1871,6 +1871,7 @@ pub mod problem_2496_maximum_value_of_a_string_in_an_array;
18711871
pub mod problem_2497_maximum_star_sum_of_a_graph;
18721872
pub mod problem_2498_frog_jump_ii;
18731873
pub mod problem_2500_delete_greatest_value_in_each_row;
1874+
pub mod problem_2501_longest_square_streak_in_an_array;
18741875

18751876
#[cfg(test)]
18761877
mod test_utilities;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
use std::collections::HashMap;
6+
7+
impl Solution {
8+
pub fn longest_square_streak(nums: Vec<i32>) -> i32 {
9+
let mut nums = nums.into_iter().map(|x| x as u32).collect::<Vec<_>>();
10+
11+
nums.sort_unstable_by(|lhs, rhs| rhs.cmp(lhs));
12+
13+
let mut lengths = HashMap::new();
14+
let mut result = 0_u32;
15+
16+
for num in nums {
17+
let length = num
18+
.checked_mul(num)
19+
.and_then(|squared| lengths.get(&squared))
20+
.copied()
21+
.unwrap_or(0)
22+
+ 1;
23+
24+
lengths.insert(num, length);
25+
result = result.max(length);
26+
}
27+
28+
if result < 2 { -1 } else { result as _ }
29+
}
30+
}
31+
32+
// ------------------------------------------------------ snip ------------------------------------------------------ //
33+
34+
impl super::Solution for Solution {
35+
fn longest_square_streak(nums: Vec<i32>) -> i32 {
36+
Self::longest_square_streak(nums)
37+
}
38+
}
39+
40+
#[cfg(test)]
41+
mod tests {
42+
#[test]
43+
fn test_solution() {
44+
super::super::tests::run::<super::Solution>();
45+
}
46+
}
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod dynamic_programming;
2+
3+
pub trait Solution {
4+
fn longest_square_streak(nums: Vec<i32>) -> i32;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(&[4, 3, 6, 16, 8, 2] as &[_], 3), (&[2, 3, 5, 6, 7], -1)];
13+
14+
for (nums, expected) in test_cases {
15+
assert_eq!(S::longest_square_streak(nums.to_vec()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)