LeetCode 1124:Longest Well-Performing Interval

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
分享一道华为爸爸的面试题,今年华为面试规范好多,也难了好多。这是我秋招华为一面的题目,当时第一个想法是动态规划(因为之前也没遇到过这一题),然后按照动态规划的方法去做了,答案当然是面试官知道这种方法不行,总结下就是动态规划无法求出这道题的最长串,比如[9,9,6,0,6,6,9,9,9,9,9,9,9]的答案是整个数组,而用动态规划求出的会是最后的那一串9,这当然是不符合题目要求的(面试时支支吾吾没想出办法,给了个大概思路,后来回到学校和一个妹子讨论竟然被她百度出是leetcode原题,吐血,不过感谢面试官竟然让我面了终面,今早华为官网看了看竟然录用排序了?)。
说一下这道题目,解决这种最长字串的问题,第一选择的方法应该就是最小栈(也是那妹子说的)。先将数组中大于8的数置为1,其他置为-1。然后计算从数组起始位置到当前位置数组的和sum,在遍历数组的过程中用先判断当前的sum是否之前出现过,如果没有出现,就记录下来(用一个map,里面存放sum和数组对应的下标),最后,sum-1到sum之间的字串都是符合条件的字串。

C++
int longestWPI(vector<int>& hours) {
        map<int,int> m_sumindex;
        int sumer = 0;
        int res = 0;
        for(int i = 0;i < hours.size();++i)
        {
            sumer += hours[i] > 8 ? 1 : -1;
            if(sumer > 0)
                res = i + 1;
            if(m_sumindex.find(sumer) == m_sumindex.end())
                m_sumindex[sumer] = i;
            if(m_sumindex.find(sumer-1) != m_sumindex.end())
                res = max(res,i - m_sumindex[sumer-1]);
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值