[Daily Coding Problem 224] Find smallest positive integer that is not the sum of a subset of a sorte...

本文介绍了一种线性时间复杂度O(N)的方法来找出一个非负整数有序数组中无法通过任何子集相加得到的最小正整数。此算法避免了NP完全问题的子集求和,并通过迭代更新最小不可能和来实现。文中还提供了具体的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a sorted array of non-negative integers, find the smallest positive integer that is not the sum of a subset of the array.

For example, for the input [1, 2, 3, 10], you should return 7.

Do this in O(N) time.

 

A naive solution would be to start with 1 and keep incrementing until we find a solution. However, since the problem of determining whether a subset of an array sums to a given number is NP-complete, this approach cannot succeed in linear time. 

There is a pesudo polynomial solution with dynamic programming for the subset sum problem.  This is still not real linear time as the target can be pretty big.

 

O(N) solution

1. Initialize the smallest impossible sum to be 1.

2. Iterate through the input array, for each element, do the following:

2(a). if a[i] <= smallest impossible sum, increment the smallest impossible sum by a[i];

2(b). if a[i] > smallest impossible sum, return smallest impossible sum;

 

Why does this alogrithm work? 

At any given point of smallest impossible sum k, we know we already can make any non-negative sum from 0 to k - 1. As long as a[i] <= k, we can get k, k + 1, k + 2,..... k - 1 + a[i], and the smallest impossible sum becomes k - 1 + a[i] + 1. However, if a[i] > k, then we can only get 1, 2,.... k - 1, a[i], a[i] + 1, a[i] + 2, ....., a[i] + k - 1. Since a[i] > k, there is a gap! k is the smallest positive integer that is not covered by any subset sum.

 

public int smallestPositiveInteger(int[] a) {
    if(a == null || a.length == 0) {
        return 1;
    }
    int impossible_sum = 1;
    for(int i = 0; i < a.length; i++) {
        if(a[i] <= impossible_sum) {
            impossible_sum += a[i];
        }
        else {
            break;
        }
    }
    return impossible_sum;
}

 

转载于:https://www.cnblogs.com/lz87/p/11162186.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值