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 = count(begin(nums), end(nums), 0);
    const int ones = nums.size() - zeros;
    vector<int> ans{0};  // 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;
    // Division at index 0
    List<Integer> ans = new ArrayList<>(Arrays.asList(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<>(Arrays.asList(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]  # 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