1589. 所有排列中的最大和

leetcode 1589. 所有排列中的最大和

题目链接


问题描述

  • 题目描述:
      有一个整数数组 nums ,和一个查询数组 requests ,其中 requests[i] = [starti, endi] 。第 i 个查询求 nums[ s t a r t i start_i starti] + nums[ s t a r t i + 1 start_i + 1 starti+1] + ... + nums[ e n d i − 1 end_i - 1 endi1] + nums[ e n d i end_i endi] 的结果 , s t a r t i start_i starti e n d i end_i endi 数组索引都是 从 0 开始 的。
    你可以任意排列 nums 中的数字,请你返回所有查询结果之和的最大值。
    由于答案可能会很大,请你将它对 1 0 9 + 7 10^9+7 109+7 取余 后返回
  • 参数要求:
    n = = n u m s . l e n g t h n == nums.length n==nums.length
    1 < = n < = 1 0 5 1 <= n <= 10^5 1<=n<=105
    0 < = n u m s [ i ] < = 1 0 5 0 <= nums[i] <= 10^5 0<=nums[i]<=105
    1 < = r e q u e s t s . l e n g t h < = 1 0 5 1 <= requests.length <= 10^5 1<=requests.length<=105
    r e q u e s t s [ i ] . l e n g t h = = 2 requests[i].length == 2 requests[i].length==2
    0 < = s t a r t i < = e n d i < n 0 <= start_i <= end_i < n 0<=starti<=endi<n

思路

  1. 首先需要求出的一种排列可能(实际上可能存在多种排列)需要满足以下条件,即按照对应区间求和最大
  2. 在分析区间中我们不难发现,对于requests中重复最多的下标降序排列,得到一个数组count,如果要使得最后的结果最大,那就要用最大的count搭配nums中未被使用最大的元素。
  3. 因此需要对nums递增排序,并且排序并不影响结果。
  4. 这里需要注意的是,统计count的方法,如果是直接统计,也就是以遍历的方式统计,那么最后会出现超时。例如:对于request[i]的统计
 			int start = requests[i][0];
            int end = requests[i][1];
            while (start<=end){
                Integer count = map.getOrDefault(start,0);//如果没有就返回0
                map.put(start,count+1);
                start++;
            }
  1. 因此采用差分数组统计区间次数,最后通过一次前缀数组就可以获得每一个下标的包含的次数。类似题目1109. 航班预订统计

代码

public int maxSumRangeQuery(int[] nums, int[][] requests) {
        int len = nums.length;
        Arrays.sort(nums);
        int[] count = new int[len];
        for (int i = 0; i < requests.length; i++) {
            int start = requests[i][0];
            int end = requests[i][1];
            count[start]++;
            if (end<len-1){
                count[end+1]--;
            }
        }
        for (int i = 1; i < len; i++) {
            count[i] += count[i-1];
        }
        Arrays.sort(count);
        long res = 0;
        int mod = (int)1e9+7;
        int indexCount = len-1;
        int indexNum = len-1;
        while (indexCount>=0&&count[indexCount]!=0){
            res = (res+(long)nums[indexNum]*count[indexCount])%mod;
            indexCount--;
            indexNum--;
        }
        return (int)res;
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值