leetcode 1124.表现良好的最长时间段(longest well performing interval)C语言
1.description
https://leetcode-cn.com/problems/longest-well-performing-interval/description/
给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。
我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。
所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。
请你返回「表现良好时间段」的最大长度。
示例 1:
输入:hours = [9,9,6,0,6,6,9]
输出:3
解释:最长的表现良好时间段是 [9,9,6]。
提示:
1 <= hours.length <= 10000
0 <= hours[i] <= 16
2.solution
涉及了前缀和、单调栈,参考 这里
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int longestWPI(int* hours, int hoursSize){
for(int i=0; i<hoursSize; ++i){
hours[i] = hours[i] > 8 ? 1 : -1;
}
// 构造前缀和
int *presum = (int*)malloc(sizeof(int)*(hoursSize+1));
presum[0] = 0;
for(int i=1; i<hoursSize+1; ++i){
presum[i] = presum[i-1] + hours[i-1];
}
// 构造presum的单调栈
int *stack = (int*)malloc(sizeof(int)*(hoursSize+1));
int top = 0;
stack[top] = 0;
for(int i=1; i<hoursSize+1; ++i){
if(presum[i]<presum[stack[top]]){
top++;
stack[top] = i;
}
}
int res = hours[0] == 1 ? 1 : 0;
for(int i=hoursSize; i>=0; --i){
if(presum[i]>presum[stack[top]]){
res = MAX(res, i-stack[top]);
top--;
i++;
if(top == -1){
break;
}
}
}
return res;
}