1124. Longest Well-Performing Interval

We are given hours, a list of the number of hours worked per day for a given employee.

A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.

A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.

Return the length of the longest well-performing interval.

 

Example 1:

Input: hours = [9,9,6,0,6,6,9]
Output: 3
Explanation: The longest well-performing interval is [9,9,6].

 

Constraints:

  • 1 <= hours.length <= 10000
  • 0 <= hours[i] <= 16

Rust Solution

struct Solution;
use std::collections::HashMap;

impl Solution {
    fn longest_wpi(hours: Vec<i32>) -> i32 {
        let n = hours.len();
        let mut hm: HashMap<i32, usize> = HashMap::new();
        let mut score = 0;
        let mut res = 0;
        for i in 0..n {
            score += if hours[i] > 8 { 1 } else { -1 };
            if score > 0 {
                res = i + 1;
            } else {
                hm.entry(score).or_insert(i);
                if let Some(j) = hm.get(&(score - 1)) {
                    res = res.max(i - j);
                }
            }
        }
        res as i32
    }
}

#[test]
fn test() {
    let hours = vec![9, 9, 6, 0, 6, 6, 9];
    let res = 3;
    assert_eq!(Solution::longest_wpi(hours), res);
}

Having problems with this solution? Click here to submit an issue on github.