[LeetCode] All Divisions With the Highest Score of a Binary Array

2155. All Divisions With the Highest Score of a Binary Array

You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:

  • numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive).
  • If i == 0, numsleft is empty, while numsright has all the elements of nums.
  • If i == n, numsleft has all the elements of nums, while numsright is empty.

The division score of an index i is the sum of the number of 0’s in numsleft and the number of 1’s in numsright.

Return all distinct indices that have the highest possible division score. You may return the answer in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<int> maxScoreIndices(vector<int>& A) {
int n = A.size(), ma = -1;
vector<int> lpsum(n), rpsum(n), res;
for(int i = 0; i < n; i++) {
lpsum[i] = (i ? lpsum[i-1] : 0) + (A[i] == 0);
}
for(int i = n - 1; i >= 0; i--) {
rpsum[i] = (i + 1 < n ? rpsum[i+1] : 0) + (A[i] == 1);
}
for(int i = -1; i < n; i++) {
int sum = (i >= 0 ? lpsum[i] : 0) + (i + 1 < n ? rpsum[i+1] : 0);
if(sum == ma) res.push_back(i+1);
else if(sum > ma) {
ma = sum;
res.clear();
res.push_back(i+1);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/30/PS/LeetCode/all-divisions-with-the-highest-score-of-a-binary-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.