ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

[Oracle] LeetCode 1802 Maximum Value at a Given Index in a Bounded Array

2022-08-23 06:30:08  阅读:257  来源: 互联网

标签:Index Given right 1802 idx nums series AP val


You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:

  • nums.length == n
  • nums[i] is a positive integer where 0 <= i < n.
  • abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.
  • The sum of all the elements of nums does not exceed maxSum.
  • nums[index] is maximized.

Return nums[index] of the constructed array.

Solution

二分答案。从贪心的角度出发,我们可能构成的序列,必须是以 \(index\) 为中心,然后左右都是等差数列直到 \(1\).

点击查看代码
class Solution {
private:
    #define ll long long
    bool check(ll val, int n, int idx, ll maxSum){
        int N_left_to_idx = idx;
        int N_right_to_end = (n-1)-(idx+1)+1;
        
        int AP_series = val-1; // from 1 to val-1
        int N_left_ones = 0, N_right_ones = 0;
        ll leftsum=0, rightsum=0;
        
        if(N_left_to_idx>=AP_series){
            // can contain the whole AP series
            leftsum = (val-1)*val/2;
            N_left_ones = N_left_to_idx - AP_series;
        }
        else{
            // cannot contain the whole AP series
            // AP starts from val-1 to val-idx
            leftsum = N_left_to_idx * (val-1+val-idx)/2;
        }
        
        if(N_right_to_end >= AP_series){
            rightsum = (val-1)*val/2;
            N_right_ones = N_right_to_end - AP_series;
        }
        else{
            rightsum = N_right_to_end*(val-1+val-N_right_to_end)/2;
        }
        return rightsum+leftsum+N_left_ones+N_right_ones+val<=maxSum;
        
    }
public:
    int maxValue(int n, int index, ll maxSum) {
        ll l = 1, r = maxSum;
        int ans=0;
        while(l<=r){
            ll mid = (r-l)/2+l;
            if(check(mid, n, index, maxSum)){
                ans=mid; l=mid+1;
            }
            else r=mid-1;
        }
        return ans;
    }
};

标签:Index,Given,right,1802,idx,nums,series,AP,val
来源: https://www.cnblogs.com/xinyu04/p/16614824.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有