7

Given a sorted array, find the smallest positive integer that is not the sum of...

 1 year ago
source link: https://www.coderzheaven.com/2023/06/27/given-a-sorted-array-find-the-smallest-positive-integer-that-is-not-the-sum-of-a-subset-of-the-array/?amp%3Butm_medium=rss&%3Butm_campaign=given-a-sorted-array-find-the-smallest-positive-integer-that-is-not-the-sum-of-a-subset-of-the-array
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

  • Youtube Videos
  • Videos
  • Channels
  • Receives
  • How to javascript
  • Integer

Java

public class SmallestPositiveInteger {
    public static int findSmallestPositiveInteger(int[] nums) {
        int smallest = 1;
        for (int num : nums) {
            if (num <= smallest) {
                smallest += num;
            } else {
                break;
            }
        }
        return smallest;
    }
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 10};
        int result = findSmallestPositiveInteger(nums);
        System.out.println(result); // Output: 7
    }
}

Javascript

function findSmallestPositiveInteger(nums) {
    let smallest = 1;
    for (let num of nums) {
        if (num <= smallest) {
            smallest += num;
        } else {
            break;
        }
    }
    return smallest;
}
const nums = [1, 2, 3, 10];
const result = findSmallestPositiveInteger(nums);
console.log(result); // Output: 7

Python:

def find_smallest_positive_integer(nums):
    smallest = 1
    for num in nums:
        if num <= smallest:
            smallest += num
        else:
            break
    return smallest
nums = [1, 2, 3, 10]
result = find_smallest_positive_integer(nums)
print(result) # Output: 7

The solution iterates through the sorted array and updates the value of the smallest variable. It adds each number from the array to smallest if the number is less than or equal to smallest. If the number is greater than smallest, it breaks out of the loop. Finally, it returns the value of smallest, which represents the smallest positive integer that cannot be formed by a subset of the given sorted array.

Asked by: Amazon


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK