Skip to content

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

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  vector<int> maxScoreIndices(vector<int>& nums) {
    const int zeros = ranges::count(nums, 0);
    const int ones = nums.size() - zeros;
    vector<int> ans{0};  // the division at index 0
    int leftZeros = 0;
    int leftOnes = 0;
    int maxScore = ones;  // `leftZeros` + `rightOnes`

    for (int i = 0; i < nums.size(); ++i) {
      leftZeros += nums[i] == 0;
      leftOnes += nums[i] == 1;
      const int rightOnes = ones - leftOnes;
      const int score = leftZeros + rightOnes;
      if (maxScore == score) {
        ans.push_back(i + 1);
      } else if (maxScore < score) {
        maxScore = score;
        ans = {i + 1};
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public List<Integer> maxScoreIndices(int[] nums) {
    final int ones = Arrays.stream(nums).sum();
    final int zeros = nums.length - ones;
    // the division at index 0
    List<Integer> ans = new ArrayList<>(List.of(0));
    int leftZeros = 0;
    int leftOnes = 0;
    int maxScore = ones; // `leftZeros` + `rightOnes`

    for (int i = 0; i < nums.length; ++i) {
      leftZeros += nums[i] == 0 ? 1 : 0;
      leftOnes += nums[i] == 1 ? 1 : 0;
      final int rightOnes = ones - leftOnes;
      final int score = leftZeros + rightOnes;
      if (maxScore == score) {
        ans.add(i + 1);
      } else if (maxScore < score) {
        maxScore = score;
        ans = new ArrayList<>(List.of(i + 1));
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
  def maxScoreIndices(self, nums: list[int]) -> list[int]:
    zeros = nums.count(0)
    ones = len(nums) - zeros
    ans = [0]  # the division at index 0
    leftZeros = 0
    leftOnes = 0
    maxScore = ones  # `leftZeros` + `rightOnes`

    for i, num in enumerate(nums):
      leftZeros += num == 0
      leftOnes += num == 1
      rightOnes = ones - leftOnes
      score = leftZeros + rightOnes
      if maxScore == score:
        ans.append(i + 1)
      elif maxScore < score:
        maxScore = score
        ans = [i + 1]

    return ans