Skip to content

Commit

Permalink
1781. Sum of Beauty of All Substrings: AC
Browse files Browse the repository at this point in the history
  • Loading branch information
tan-wei committed Nov 28, 2024
1 parent 47b4886 commit f1b0879
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/solution/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1342,3 +1342,4 @@ mod s1775_equal_sum_arrays_with_minimum_number_of_operations;
mod s1776_car_fleet_ii;
mod s1779_find_nearest_point_that_has_the_same_x_or_y_coordinate;
mod s1780_check_if_number_is_a_sum_of_powers_of_three;
mod s1781_sum_of_beauty_of_all_substrings;
89 changes: 89 additions & 0 deletions src/solution/s1781_sum_of_beauty_of_all_substrings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* [1781] Sum of Beauty of All Substrings
*
* The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.
*
* For example, the beauty of "abaacc" is 3 - 1 = 2.
*
* Given a string s, return the sum of beauty of all of its substrings.
*
* Example 1:
*
* Input: s = "aabcb"
* Output: 5
* Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.
* Example 2:
*
* Input: s = "aabcbaa"
* Output: 17
*
*
* Constraints:
*
* 1 <= s.length <=^ 500
* s consists of only lowercase English letters.
*
*/
pub struct Solution {}

// problem: https://leetcode.com/problems/sum-of-beauty-of-all-substrings/
// discuss: https://leetcode.com/problems/sum-of-beauty-of-all-substrings/discuss/?currentPage=1&orderBy=most_votes&query=

// submission codes start here

impl Solution {
pub fn beauty_sum(s: String) -> i32 {
let s = s.chars().collect::<Vec<char>>();
let n = s.len();
let mut memo = vec![vec![0; 26]; n + 1];

for i in 0..n {
memo[i + 1] = memo[i].clone();
memo[i + 1][s[i] as usize - 'a' as usize] += 1;
}

let mut result = 0;
for i in 0..n {
for j in i..n {
let mut max = 0;
let mut min = n + 10;

for k in 0..26 {
let v = memo[j + 1][k] - memo[i][k];
max = max.max(v);
if v != 0 {
min = min.min(v);
}
}
result += max - min;
}
}

result as i32
}
}

// submission codes end

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

#[test]
fn test_1781_example_1() {
let s = "aabcb".to_string();

let result = 5;

assert_eq!(Solution::beauty_sum(s), result);
}

#[test]
fn test_1781_example_2() {
let s = "aabcbaa".to_string();

let result = 17;

assert_eq!(Solution::beauty_sum(s), result);
}
}

0 comments on commit f1b0879

Please sign in to comment.