Leetcode 1413. Minimum Value to Get Positive Step by Step Sum
You are given an integer array nums
. In one operation, you can choose any integer x
and add it to any element of the array. Your goal is to make the sum of the array elements positive at each step. Return the minimum value that ensures this.
Example:
Input: nums = [-3, 2, -3, 4, 2]
Output: 5
Explanation: If you start with the minimum positive integer `5`, the running sum array would be [2, 4, 1, 5, 7] which is always positive.
nums
be empty?
nums
contains at least one element.nums
?
nums
are integers and can be positive, negative, or zero.To solve the problem, our strategy is to ensure that the cumulative sum of the array remains positive through all steps. We’ll do this by finding the minimum cumulative sum in the array and adjusting the starting point accordingly.
x
to make all cumulative sums positive.x
which makes the starting sum positive. This is obtained by ensuring the lowest cumulative sum, when adjusted by x
, is greater than zero.#include <vector>
#include <algorithm>
#include <iostream>
class Solution {
public:
int minStartValue(std::vector<int>& nums) {
int minSum = 0;
int currentSum = 0;
for (int num : nums) {
currentSum += num;
minSum = std::min(minSum, currentSum);
}
// To make sure all cumulative sums are positive, minSum + starting value should be > 0.
// Therefore, starting value > -minSum, we need to take ceil to make it positive integer
return 1 - minSum;
}
};
int main() {
Solution solution;
std::vector<int> nums = {-3, 2, -3, 4, 2};
std::cout << solution.minStartValue(nums) << std::endl; // Output: 5
return 0;
}
This completes the explanation and solution for the problem “Minimum Value to Get Positive Step by Step Sum”.
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?