一、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
方法一:前綴和
簡化問題:題目要求的是區間中 的數字嚴格大於 的數字最大區間,可把 和 的數字分別設置爲 1、-1,這樣問題就轉化爲求區間中總和 > 0 的最長區間;而區間總和可用前綴和優化掉 時間求子區間的時間
剪枝:這裏因爲求的是最大長度,所以一旦找到了一個最大和區間,可立即退出第二重循環,這是因爲區間長度變短,總和不會變大
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;
}
}
複雜度分析
- 時間複雜度:,極端情況是 ,但由於有剪枝,所以一般情況下會快很多
- 空間複雜度:,
方法二:Map 記錄前綴和位置
[9,9, 6, 0,9, 6,9]
[1,1,-1,-1,1,-1,1]
[0,1, 2, 3,4, 5,6]
複雜度分析
- 時間複雜度:,
- 空間複雜度:,