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.
1public class Solution {
2 public int minStartValue(int[] nums) {
3 int minSum = 0, currentSum = 0;
4 for (int num : nums) {
5 currentSum += num;
6 if (currentSum < minSum) {
7 minSum = currentSum;
8 }
9 }
10 return 1 - minSum;
11 }
12
13 public static void main(String[] args) {
14 Solution sol = new Solution();
15 int[] nums = {-3, 2, -3, 4, 2};
16 System.out.println(sol.minStartValue(nums)); // Output: 5
17 }
18}
This Java implementation tracks the ongoing cumulative sum throughout the for-loop. The minimum cumulative sum value is used to determine the smallest positive start value needed to keep the running sum >= 1.
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).
The prefix sum is maintained over the iteration, comparing against a minimum threshold. The necessary start value ensures this cumulative prefix never dips below one during any point.