Maximum period of good behavior

Hours, which records the number of hours an employee works every day. We consider a “tired day” when employees work more than eight hours a day. The so-called “good performance period” means that during this period, the “tired days” is strictly greater than the “not tired days.” Return the maximum length of a good time period.

The problem solving code

If it is greater than 8, change it to + 1; if it is less than -1, change it to prefix and. Then solve the number of the current position to find the previous position of the number smaller than it. The current range is a range greater than or equal to 0

  1. ,9,6,0,6,6,9 [9]
  2. [1, 1, 1, 1, 1, 1, 1]
  3. The [0,1,2,1,0-1,-2,-1] prefix and sequence start require an additional 0
var longestWPI = function(hours) {
  let stack = []; // +1 -1 sequence
  let sum = [0]; // prefix and sequence, plus an extra 0
  hours.forEach(v= > stack.push(v > 8 ? 1 : -1)); // Convert to +1 -1
  stack.forEach(v= > sum.push(v + sum[sum.length - 1])); // Convert to prefix and
  let max = 0;
  for (let i = sum.length - 1; i >= 0;  i--) {
    const num = sum[i];
    for (let j = i - 1; j >= 0 ; j--) { // Select the value less than subscript n from position n to position 0-n
      const element = sum[j];
      if (element < num ) {
        max = Math.max(max,i - j);
      } else continue; }}return max;
};
Copy the code