diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 40208f8..fab33b1 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -231,4 +231,5 @@ mod p3176_find_the_maximum_length_of_a_good_subsequence_i; mod p3177_find_the_maximum_length_of_a_good_subsequence_ii; mod p977_squares_of_a_sorted_array; mod p2181_merge_nodes_in_between_zeros; -mod p2552_count_increasing_quadruplets; \ No newline at end of file +mod p2552_count_increasing_quadruplets; +mod p2555_maximize_win_from_two_segments; \ No newline at end of file diff --git a/src/problem/p2555_maximize_win_from_two_segments.rs b/src/problem/p2555_maximize_win_from_two_segments.rs new file mode 100644 index 0000000..94b4a29 --- /dev/null +++ b/src/problem/p2555_maximize_win_from_two_segments.rs @@ -0,0 +1,52 @@ +/** + * [2555] Maximize Win From Two Segments + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn maximize_win(prize_positions: Vec, k: i32) -> i32 { + let n = prize_positions.len(); + let mut dp = vec![0;n + 1]; + let mut result = 0; + + for i in 0..n { + let j = Self::binary_search(&prize_positions, prize_positions[i] - k); + result = result.max(i - j + 1 + dp[j]); + + dp[i + 1] = dp[i].max(i - j + 1); + } + + result as i32 + } + + fn binary_search(array: &Vec, target: i32) -> usize { + let (mut left, mut right) = (0, array.len()); + + while left < right { + let middle = left + (right - left) / 2; + if array[middle] < target { + left = middle + 1; + } else { + right = middle; + } + } + + left + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_2555() { + assert_eq!(7, Solution::maximize_win(vec![1,1,2,2,3,3,5], 2)); + assert_eq!(2, Solution::maximize_win(vec![1,2,3,4], 0)); + } +}