Rearrange array to maximize positive prefix sums
Company: SoFi
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Take-home Project
Quick Answer: This question evaluates array manipulation, prefix-sum reasoning, and greedy/combinatorial optimization skills for maximizing a permutation-based metric in the Coding & Algorithms category.
Constraints
- 1 <= len(a) <= 2 * 10^5
- -10^9 <= a[i] <= 10^9
Examples
Input: [2, -1, 2, -3]
Expected Output: 3
Explanation: Sorting in descending order gives [2, 2, -1, -3]. The prefix sums are 2, 4, 3, 0, so 3 prefix sums are positive.
Input: [-5]
Expected Output: 0
Explanation: The only prefix sum is -5, which is not positive.
Input: [-5, 10]
Expected Output: 2
Explanation: An optimal order is [10, -5]. The prefix sums are 10 and 5, and both are positive.
Input: [0, 0, 5, -6, 1]
Expected Output: 4
Explanation: Sorting descending gives [5, 1, 0, 0, -6]. The prefix sums are 5, 6, 6, 6, 0, so the answer is 4.
Input: [-1, -1, -1, 4]
Expected Output: 4
Explanation: Sorting descending gives [4, -1, -1, -1]. The prefix sums are 4, 3, 2, 1, so all 4 prefixes are positive.
Input: [0, 0, 0]
Expected Output: 0
Explanation: Every prefix sum is 0, and 0 is not considered positive.
Hints
- For any fixed prefix length `k`, which choice of `k` elements gives the largest possible prefix sum?
- Compare the prefix sum at each index after sorting in non-increasing order with the prefix sum at the same index in any other permutation.