zoukankan      html  css  js  c++  java
  • [LeetCode 1121] Divide Array Into Increasing Sequences

    Given a non-decreasing array of positive integers nums and an integer K, find out if this array can be divided into one or more disjoint increasing subsequences of length at least K.

    Example 1:

    Input: nums = [1,2,2,3,3,4,4], K = 3
    Output: true
    Explanation: 
    The array can be divided into the two subsequences [1,2,3,4] and [2,3,4] with lengths at least 3 each.
    

    Example 2:

    Input: nums = [5,6,6,7,8], K = 3
    Output: false
    Explanation: 
    There is no way to divide the array using the conditions required.
    

    Note:

    1. 1 <= nums.length <= 10^5
    2. 1 <= K <= nums.length
    3. 1 <= nums[i] <= 10^5

    Algorithm: Do a linear scan to find the count number of the most frequent integers and denote this count as C. This array can be divided into one or more disjoint increasing subsequences if and only if C * K <= n.

    Proof of correctness:

    1. Necessary condition: If we are given C * K <= n, then we can always try the following division.  For nums[i], assign it to group[i % C]. Since there are C groups in total, this assignment guarantees that all duplicated integers will be assigned to different groups. This ensures each group meets the increasing requirement. Also because C * K <= n, this means each group will get at least K integers, this meets the length of at least K requirement.

    2. Sufficient condition: If the array can be divided into one or more disjoint increasing subsequences, then what can we conclude about the total number of integers n? Well, there will be two cases here. Case 1 is that there is no duplicated elements in the array. As long as n >= K, we can meet the division requirement. Case 2 is that there are duplicated elements in the array. Again, let C denotes the count of the most frequent duplicated integer i. In order to meet the division requirement, we must have at least C different subsequences so that each i is put in a different group. This means n must >= C * K. In fact, case 1 is just a special case of case 2 with C = 1. So n >= C * K.

    class Solution {
        public boolean canDivideIntoSubsequences(int[] A, int K) {
            int cur = 1, groups = 1, n = A.length;
            for (int i = 1; i < n; i++) {
                cur = A[i - 1] < A[i] ?  1 : cur + 1;
                groups = Math.max(groups, cur);
            }
            return n >= K * groups;    
        }
    } 
  • 相关阅读:
    redis单机安装以及简单redis集群搭建
    Linux中JDK安装教程
    微信公众号开发(一)
    easyui多图片上传+预览切换+支持IE8
    mybatis动态sql之foreach标签
    java List递归排序,传统方式和java8 Stream优化递归,无序的列表按照父级关系进行排序(两种排序类型)
    java钉钉通讯录同步
    java使用poi生成导出Excel(新)
    java 图片转base64字符串、base64字符串转图片
    Spring事务mysql不回滚:mysql引擎修改
  • 原文地址:https://www.cnblogs.com/lz87/p/11191912.html
Copyright © 2011-2022 走看看