LeetCode 1124:表现良好的最长时间段(Longest Well-Performing Interval)解法汇总

文章目录

  • My Solution

更多LeetCode题解

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

My Solution

  1. 将每一天转换为是否tiring,tiring为1,非tiring为-1,问题转换为寻找tiring数组中和大于0的最长区间。
  2. 采用暴力法,对每一个区间求和,但是这样会TLE。复杂度是 O ( n 3 ) O(n^3) O(n3)
  3. 注意到对每一个区间,并不需要重新求和,因为相对于前一个区间来说,只增加了一个末尾位置的数字,所以只需将前一区间的和保留,就可以降低复杂度到 O ( n 2 ) O(n^2) O(n2)
class Solution {
public:
	int longestWPI(vector<int>& hours) {
		vector<int> tiring;
		int res = 0;
		for (int h : hours) {
			if (h > 8)
				tiring.push_back(1);
			else
				tiring.push_back(-1);
		}
		for (int i = 0; i < tiring.size(); i++) {
			int sum = 0;
			for (int j = i; j < tiring.size(); j++) {
				//int sum = accumulate(tiring.begin() + i, tiring.begin() + j + 1, 0);//Time Limit Exceeded
				sum += tiring[j];
				if ( sum > 0 && (j-i+1)>res) {
					res = j-i+1;
				}
			}
		}
		return res;
	}
};

你可能感兴趣的:(LeetCode刷题题解记录)