Skip to content

Commit

Permalink
Add problem 1802: Maximum Value at a Given Index in a Bounded Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 16, 2023
1 parent 198dd1c commit d9f7c4a
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1419,6 +1419,7 @@ pub mod problem_1790_check_if_one_string_swap_can_make_strings_equal;
pub mod problem_1791_find_center_of_star_graph;
pub mod problem_1796_second_largest_digit_in_a_string;
pub mod problem_1800_maximum_ascending_subarray_sum;
pub mod problem_1802_maximum_value_at_a_given_index_in_a_bounded_array;
pub mod problem_1805_number_of_different_integers_in_a_string;
pub mod problem_1807_evaluate_the_bracket_pairs_of_a_string;
pub mod problem_1812_determine_color_of_a_chessboard_square;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
fn get_area(start: u64, end: u64) -> u64 {
(start + end) * (end + 1 - start) / 2
}

#[allow(clippy::cast_precision_loss)]
pub fn max_value(n: i32, index: i32, max_sum: i32) -> i32 {
let n = n as u32;
let index = index as u32;
let index = index.min(n - 1 - index);
let max_sum = max_sum as u32 - n;
let n_u64 = u64::from(n);
let index_u64 = u64::from(index);
let max_sum_u64 = u64::from(max_sum);

(if max_sum_u64 <= (index_u64 + 1).pow(2) {
f64::from(max_sum).sqrt() as u32
} else {
let threshold =
Self::get_area(1, n_u64 - index_u64) + Self::get_area(n_u64 - index_u64 * 2, n_u64 - index_u64 - 1);

if max_sum_u64 <= threshold {
(f64::sqrt((8 * (max_sum_u64 + index_u64 * (index_u64 + 1)) + 1) as _) as u32 - index * 2 - 1) / 2
} else {
n - index + (max_sum - threshold as u32) / n
}
} + 1) as _
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn max_value(n: i32, index: i32, max_sum: i32) -> i32 {
Self::max_value(n, index, max_sum)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod mathematical;

pub trait Solution {
fn max_value(n: i32, index: i32, max_sum: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [((4, 2, 6), 2), ((6, 1, 10), 3), ((4, 0, 4), 1), ((5, 0, 28), 7)];

for ((n, index, max_sum), expected) in test_cases {
assert_eq!(S::max_value(n, index, max_sum), expected);
}
}
}

0 comments on commit d9f7c4a

Please sign in to comment.