leetcode 1124.表现良好的最长时间段(longest well performing interval)C语言

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值