Leetcode 1413. Minimum Value to Get Positive Step by Step Sum
You are given an integer array nums. You start with an initial value startValue = 0.
In each step, you are required to add the current element of the array to startValue.
Return the minimum positive value of startValue such that the step by step sum is always positive.
nums and its length?
nums can be of length between 1 and 100.nums can be in the range of -100 to 100.startValue such that the cumulative sum never drops to zero or below during the iteration through the array.minVal to a high positive value (e.g., Integer.MAX_VALUE) to keep track of the minimum step-by-step sum encountered during the iteration.minVal with the smallest running sum.startValue will be 1 - minVal if minVal is negative or zero. If minVal is positive, startValue will simply be 1.public class Solution {
public int minStartValue(int[] nums) {
int minVal = Integer.MAX_VALUE;
int runningSum = 0;
for (int num : nums) {
runningSum += num;
minVal = Math.min(minVal, runningSum);
}
// If minVal is negative or zero, the minimum start value to get positive sums is 1 - minVal
// If minVal is positive, the minimum start value is 1
return minVal < 1 ? 1 - minVal : 1;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {-3, 2, -3, 4, 2};
System.out.println(sol.minStartValue(nums)); // Output: 5
}
}
n is the length of the nums array. We only make a single pass through the array to compute the running sum and determine the minimum value.This strategy ensures that the solution is efficient and meets the problem’s constraints.
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?