LeetCode : Make a Positive Array Solution

Master LeetCode problem (Make a Positive Array), 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.

. Make a Positive Array

Problem Explanation

Explanation:

Given an array of integers, we need to make all elements of the array positive by performing a series of operations. In each operation, we can either increment or decrement an element by 1.

To achieve the goal, we can iterate through the array from left to right and adjust each element to be positive by considering the previous element and performing the necessary operations. The key idea is to minimize the number of operations required to make an element positive while maintaining the relative order of elements in the array.

Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(1)

Solution Code

public int[] makePositiveArray(int[] nums) {
    int operations = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] <= nums[i - 1]) {
            operations += nums[i - 1] - nums[i] + 1;
            nums[i] = nums[i - 1] + 1;
        }
    }
    return nums;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode (Make a Positive Array)?

This page provides optimized solutions for LeetCode problem (Make a Positive Array) 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 (Make a Positive Array)?

The time complexity for LeetCode (Make a Positive Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode in Java, C++, or Python.

Back to LeetCode Solutions