HackerRank: Non-Divisible Subset

该博客主要讨论了在HackerRank上的一个算法挑战——如何找到一个非可除子集。关键点在于处理remainder数组,特别是当k为偶数时,remainder[k/2]应设为1,并且从remainder[0]中最多只能选择一个元素。博主深入探讨了如何应用这些考虑事项来解决问题。
摘要由CSDN通过智能技术生成

考虑事项:

  • remainder[k/2] = 1
  • remainder[0] 里面只能抽出一个
  • 即 remainder[0] = std::min(remainder[0], 1)
  • and remainder[k/2] = std::min(remainder[k/2], 1) when k%2 == 0.

计算

for (int i = 0; i<=k/2, i++)
	maxRes += std::max(remainder[i], remainder[k-i]);
static int subsetPairNotDivisibleByK(int arr[], int n, int k) {
    int maximumSubset = 0;
    //creating an array with all possible remainder fo k
    int[] remainders = new int[k];

    //fill the array initially with 0
    Arrays.fill(remainders, 0);

    //loop through the array arr and get the frequency of the remainders
    for(int val: arr){
        int rem = val%k;
        remainders[rem]++;
    }
    //consider a case when k is even. eg. k=6 then remainder 3+3 is 6 so can not be cnsidered.
    if(k%2==0){
        remainders[k/2] = Math.min(remainders[k/2], 1);
    }
    //consider a case where we take number that is divisible by k into consideration,
    //there is only 1 number can be considered e.g. k=3 then we can either consider 3 or 9 both can not be considered together.
    maximumSubset = Math.min(remainders[0], 1);

    //loop through the array of remainders array and get the max of remainder[i] or remainder[i-k]
    for(int i=1;i<=k/2;i++){
        maximumSubset+=Math.max(remainders[i], remainders[k-i]);
    }

    return maximumSubset;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值