Sponsored
Sponsored
The idea is to simulate the step by step summation of the start value with the elements of the array. We maintain a running sum and adjust the start value such that this sum never drops below 1. At each step, if the running sum is less than 1, we calculate and update the new minimum start value needed to keep the running sum at least 1.
Time Complexity: O(n), where n is the length of nums.
Space Complexity: O(1), as we are using a constant amount of space.
1function minStartValue(nums) {
2 let minSum = 0, currentSum = 0;
3 for (let num of nums) {
4 currentSum += num;
5 minSum = Math.min(minSum, currentSum);
6 }
7 return 1 - minSum;
8}
9
10// Example usage:
11const nums = [-3, 2, -3, 4, 2];
12console.log(minStartValue(nums)); // Output: 5
This JavaScript approach calculates a running sum through the nums array and keeps track of the minimum value encountered. The final start value ensures the step by step sum does not fall below 1 throughout the iterations.
This approach is similar to the first but conceptualized through using prefix sums and adjusting the needed start value based on the lowest prefix sum reached. We cumulatively add each number and check if the prefix sum dips below a certain threshold, indicating the minimal adjustment needed for the start value.
Time Complexity: O(n).
Space Complexity: O(1).
#include <algorithm>
using namespace std;
int minStartValue(vector<int>& nums) {
int min_prefix_sum = 0, prefix_sum = 0;
for (int num : nums) {
prefix_sum += num;
min_prefix_sum = min(min_prefix_sum, prefix_sum);
}
return 1 - min_prefix_sum;
}
int main() {
vector<int> nums = {-3, 2, -3, 4, 2};
cout << minStartValue(nums) << endl; // Output: 5
}
We track the prefix sum within the array, adjusting the minimum prefix sum found. The required start value guarantees a positive prefix sum, adjusting any negative dips accordingly.