zoukankan      html  css  js  c++  java
  • 表现良好时间段


    import java.util.HashMap;
    import java.util.Map;

    /**
    * 给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。
    * 我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。
    * 所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。
    * 请你返回「表现良好时间段」的最大长度。
    * <p>
    * 示例 1:
    * 输入:hours = [9,9,6,0,6,6,9]
    * 输出:3
    * 解释:最长的表现良好时间段是 [9,9,6]。
    * <p>
    * 提示:
    * 1 <= hours.length <= 10000
    * 0 <= hours[i] <= 16
    */
    public class _1124_LongestWPI {

    public static void main(String[] args) {
    int[] arr = {6, 9, 9, 6, 0, 6, 6, 9, 9, 9, 9};
    System.out.println(longestWPI(arr));
    }

    public static int longestWPI(int[] hours) {
    if (hours.length == 0) return 0;
    Map<Integer, Integer> map = new HashMap<>(); // key is possible sum in hours array, value is index where that sum appears for the first time
    int maxLen = 0;
    int sum = 0; // sum at index i indicates the sum of hours[0:i] after transformation

    for (int i = 0; i < hours.length; i++) {
    sum += hours[i] > 8 ? 1 : -1; // transform each hour to 1 or -1
    if (sum > 0) { // in hours[0:i], more 1s than -1s
    maxLen = i + 1;
    } else {
    if (!map.containsKey(sum)) {
    map.put(sum, i); // record where the sum appears for the first time
    }
    if (map.containsKey(sum - 1)) { // get the index j where sum of hours[0:j] is sum - 1, so that sum of hours[j+1:i] is 1
    maxLen = Math.max(maxLen, i - map.get(sum - 1));
    }
    }
    }
    return maxLen;
    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    牛客小白月赛4-E-浮点数输出 字符串
    HDU 5319 Painter(模拟)
    AtCoder Regular Contest 098 D
    strchr函数的用法
    fgets()
    格式
    Uncaught TypeError: Cannot read property 'addEventListener' of null
    window cmd下常用操作
    nuxt导入css样式
    ERROR EPERM: operation not permitted, mkdir 'C:UsersAdministratorDesktop ext uxtasic.nuxtcomponents'
  • 原文地址:https://www.cnblogs.com/laydown/p/14737354.html
Copyright © 2011-2022 走看看