LeetCode 2599: Make the Prefix Sum Non-negative Solution
Master LeetCode problem 2599 (Make the Prefix Sum Non-negative), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2599. Make the Prefix Sum Non-negative
Problem Explanation
Explanation:
Given an array of integers, we need to make the prefix sum non-negative by modifying some elements. We can achieve this by iterating through the array and adjusting the values to ensure that the prefix sum remains non-negative.
Algorithm:
- Initialize a variable
prefixSumto keep track of the cumulative sum of the array elements. - Iterate through the array and for each element:
- If the
prefixSum+ current element is negative, calculate the minimum value needed to make it non-negative. - Update the current element with the calculated minimum value.
- Update the
prefixSumwith the modified element.
- If the
- Return the modified array.
Time Complexity: O(n)
Space Complexity: O(1)
:
Solution Code
public int[] makeNonNegativePrefixSum(int[] nums) {
int prefixSum = 0;
for (int i = 0; i < nums.length; i++) {
if (prefixSum + nums[i] < 0) {
nums[i] = Math.abs(prefixSum);
}
prefixSum += nums[i];
}
return nums;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2599 (Make the Prefix Sum Non-negative)?
This page provides optimized solutions for LeetCode problem 2599 (Make the Prefix Sum Non-negative) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2599 (Make the Prefix Sum Non-negative)?
The time complexity for LeetCode 2599 (Make the Prefix Sum Non-negative) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2599 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2599 in Java, C++, or Python.