Leetcode 2996. Smallest Missing Integer Greater Than Sequential Prefix Sum
You are given a zero-based integer array arr
containing n
positive integers. You need to find the smallest positive integer greater than the sum of the elements in the prefix up to some index. More formally, you need to find the smallest integer k
such that k > arr[0] + arr[1] + ... + arr[j]
for any 0 <= j < n
.
Example:
Input: arr = [1, 2, 5, 10]
Output: 19
arr
?n
of the array?#include <iostream>
#include <vector>
int findSmallestMissingIntegerGreaterThanPrefixSum(const std::vector<int>& arr) {
int currentSum = 0;
for (int num : arr) {
currentSum += num;
}
return currentSum + 1;
}
int main() {
std::vector<int> arr = {1, 2, 5, 10};
std::cout << "Smallest Missing Integer Greater Than Prefix Sum: "
<< findSmallestMissingIntegerGreaterThanPrefixSum(arr) << std::endl;
return 0;
}
The provided example and the described problem allow us to devise a straightforward approach:
totalSum
.totalSum + 1
, because totalSum
is the sum of all elements, and any integer > totalSum
that starts only after totalSum + 1
.Steps:
The solution involves a single scan through the array to calculate the sum, which gives it a:
n
is the number of elements in the array.This approach ensures efficiency and simplicity, taking advantage of basic arithmetic operations and a single traversal through the input list.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?