【前缀和】B005_LC_表现良好的最长时间段(朴素前缀和 / Map 记录前缀和位置)

一、Problem

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.

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

二、Solution

方法一:前缀和

简化问题:题目要求的是区间中 > 8 > 8 的数字严格大于 8 \leqslant 8 的数字最大区间,可把 > 8 > 8 8 \leqslant 8 的数字分别设置为 1、-1,这样问题就转化为求区间中总和 > 0 的最长区间;而区间总和可用前缀和优化掉 O ( n ) O(n) 时间求子区间的时间

剪枝:这里因为求的是最大长度,所以一旦找到了一个最大和区间,可立即退出第二重循环,这是因为区间长度变短,总和不会变大

class Solution {
    public int longestWPI(int[] h) {
        int n = h.length, max = 0, s[] = new int[n+1];
        for (int i = 1; i <= n; i++)
            s[i] = s[i-1] + (h[i-1] > 8 ? 1 : -1);

        for (int i = 1; i <= n; i++)
        for (int j = 0; j <= i; j++) {
            if (s[i] - s[j] > 0) {    //sum=s[i]-s[j]+h[j],只不过j下标从0开始省去了+h[j]的步骤
                max = Math.max(max, i-j);
                break;
            }
        }
        return max;
    }
}

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2) ,极端情况是 O ( n 2 ) O(n^2) ,但由于有剪枝,所以一般情况下会快很多
  • 空间复杂度: O ( n ) O(n)

方法二:Map 记录前缀和位置

[9,9, 6, 0,9, 6,9]
[1,1,-1,-1,1,-1,1]
[0,1, 2, 3,4, 5,6]


复杂度分析

  • 时间复杂度: O ( ) O()
  • 空间复杂度: O ( ) O()

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/106949245
今日推荐