Skip to content

Commit

Permalink
Add problem 2280: Minimum Lines to Represent a Line Chart
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Oct 14, 2024
1 parent 550dbcc commit 75db27d
Show file tree
Hide file tree
Showing 3 changed files with 89 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 @@ -1691,6 +1691,7 @@ pub mod problem_2274_maximum_consecutive_floors_without_special_floors;
pub mod problem_2275_largest_combination_with_bitwise_and_greater_than_zero;
pub mod problem_2278_percentage_of_letter_in_string;
pub mod problem_2279_maximum_bags_with_full_capacity_of_rocks;
pub mod problem_2280_minimum_lines_to_represent_a_line_chart;

#[cfg(test)]
mod test_utilities;
49 changes: 49 additions & 0 deletions src/problem_2280_minimum_lines_to_represent_a_line_chart/dfs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
pub struct Solution;

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

impl Solution {
pub fn minimum_lines(stock_prices: Vec<Vec<i32>>) -> i32 {
let mut stock_prices = stock_prices
.into_iter()
.map(|prices| Box::<[_; 2]>::try_from(prices.into_boxed_slice()).unwrap())
.collect::<Vec<_>>();

stock_prices.sort_unstable_by_key(|prices| prices[0] as u32);

let mut prev_day = 0;
let mut prev_price = i32::MAX;
let mut prev_ratio = (1, 0);
let mut result = -1;

for stock_price in stock_prices {
let [day, price] = *stock_price;
let ratio = (price - prev_price, day - prev_day);

result +=
i32::from(i64::from(prev_ratio.0) * i64::from(ratio.1) != i64::from(prev_ratio.1) * i64::from(ratio.0));

prev_day = day;
prev_price = price;
prev_ratio = ratio;
}

result
}
}

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

impl super::Solution for Solution {
fn minimum_lines(stock_prices: Vec<Vec<i32>>) -> i32 {
Self::minimum_lines(stock_prices)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
39 changes: 39 additions & 0 deletions src/problem_2280_minimum_lines_to_represent_a_line_chart/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
pub mod dfs;

pub trait Solution {
fn minimum_lines(stock_prices: Vec<Vec<i32>>) -> i32;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(
&[[1, 7], [2, 6], [3, 5], [4, 4], [5, 4], [6, 3], [7, 2], [8, 1]] as &[_],
3,
),
(&[[3, 4], [1, 2], [7, 8], [2, 3]], 1),
(
&[
[1, 1],
[2, 2],
[3, 3],
[4, 5],
[5, 7],
[6, 6],
[7, 5],
[8, 4],
[9, 4],
[10, 4],
],
4,
),
];

for (stock_prices, expected) in test_cases {
assert_eq!(S::minimum_lines(stock_prices.iter().map(Vec::from).collect()), expected);
}
}
}

0 comments on commit 75db27d

Please sign in to comment.