LeetCode 2587: Rearrange Array to Maximize Prefix Score Solution

Master LeetCode problem 2587 (Rearrange Array to Maximize Prefix Score), 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.

2587. Rearrange Array to Maximize Prefix Score

Problem Explanation

Explanation:

To maximize the prefix score, we should rearrange the array in such a way that positive numbers are placed towards the beginning. This will increase the number of positive integers in the prefix array. To achieve this, we can follow the below algorithm:

  1. Sort the array in non-increasing order.
  2. Iterate through the sorted array and count the number of positive integers.
  3. Return the count as the maximum score.

Time Complexity: O(n log n) where n is the number of elements in the array due to sorting. Space Complexity: O(1) as we are using constant extra space.

:

Solution Code

import java.util.Arrays;

class Solution {
    public int maxScore(int[] nums) {
        Arrays.sort(nums);
        int count = 0;
        for (int num : nums) {
            if (num > 0) {
                count++;
            } else {
                break;
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2587 (Rearrange Array to Maximize Prefix Score)?

This page provides optimized solutions for LeetCode problem 2587 (Rearrange Array to Maximize Prefix Score) 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 2587 (Rearrange Array to Maximize Prefix Score)?

The time complexity for LeetCode 2587 (Rearrange Array to Maximize Prefix Score) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2587 on DevExCode?

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

Back to LeetCode Solutions