maximum-erasure-value

This commit is contained in:
Gleb Koval 2022-06-12 12:43:26 +01:00
parent d39ecf28a8
commit 2408262b66
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
2 changed files with 45 additions and 8 deletions

View File

@ -1,20 +1,37 @@
// TODO: Incomplete
struct Solution {} struct Solution {}
// TODO: Incomplete
impl Solution { impl Solution {
pub fn first_missing_positive(nums: Vec<i32>) -> i32 { pub fn first_missing_positive(nums: Vec<i32>) -> i32 {
let (max, sum) = nums let (count, max, sum) = nums
.iter() .iter()
.fold((0, 0), |(max, sum), n| { .fold((0, 0, 0), |(count, max, sum), n| {
if *n > 0 { if *n > 0 {
return (if *n > max { *n } else { max }, sum + *n); return (count + 1, if *n > max { *n } else { max }, sum + *n);
} }
(max, sum) (count, max, sum)
}); });
let missing = max * (max + 1) / 2 - sum; let expected_sum = max * (max + 1) / 2;
return if missing == 0 { max + 1 } else { missing }; let missing = max - count;
let diff = expected_sum - sum;
if diff == 0 {
max + 1
} else if missing == 1 {
diff
} else {
let min_k = missing * (missing - 1) / 2;
(1..).find(|&n| {
let k = diff - n * missing;
k >= min_k && n + k - min_k + missing <= max
}).unwrap()
}
} }
} }
fn main() { fn main() {
println!("{}", Solution::first_missing_positive(vec![99,94,96,11,92,5,91,89,57,85,66,63,84,81,79,61,74,78,77,30,64,13,58,18,70,69,51,12,32,34,9,43,39,8,1,38,49,27,21,45,47,44,53,52,48,19,50,59,3,40,31,82,23,56,37,41,16,28,22,33,65,42,54,20,29,25,10,26,4,60,67,83,62,71,24,35,72,55,75,0,2,46,15,80,6,36,14,73,76,86,88,7,17,87,68,90,95,93,97,98])); println!("{}", Solution::first_missing_positive(vec![7,9,10])); // n = 1, m = 7, k = 22
println!("{}", Solution::first_missing_positive(vec![6,5,-1,2,4,3,1])); // n = 7, m = 1, k = 0
println!("{}", Solution::first_missing_positive(vec![4,-1,1])); // n = 2, m = 2, k = 1
println!("{}", Solution::first_missing_positive(vec![4,6,-1,1])); // n = 2, m = 3, k = 4
println!("{}", Solution::first_missing_positive(vec![2,2])); // n = 2, m = 3, k = 4
} }

View File

@ -0,0 +1,20 @@
use std::collections::HashSet;
impl Solution {
pub fn maximum_unique_subarray(nums: Vec<i32>) -> i32 {
let mut l = 0;
let mut max = 0;
let mut sum = 0;
let mut exists = HashSet::new();
for r in 0..nums.len() {
sum += nums[r];
while !exists.insert(nums[r]) {
exists.remove(&nums[l]);
sum -= nums[l];
l += 1;
}
max = max.max(sum);
}
max as i32
}
}