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).
public class Solution {
public int MinStartValue(int[] nums) {
int minPrefixSum = 0, prefixSum = 0;
foreach (int num in nums) {
prefixSum += num;
minPrefixSum = Math.Min(minPrefixSum, prefixSum);
}
return 1 - minPrefixSum;
}
public static void Main() {
Solution sol = new Solution();
int[] nums = {-3, 2, -3, 4, 2};
Console.WriteLine(sol.MinStartValue(nums)); // Output: 5
}
}
By accumulating the prefix as the loop iterates and determining where this prefix is minimal, this solution adapts the starting value to keep all steps positive throughout.