[LeetCode] Maximum Score After Binary Swaps

3781. Maximum Score After Binary Swaps

You are given an integer array nums of length n and a binary string s of the same length.

Initially, your score is 0. Each index i where s[i] = '1' contributes nums[i] to the score.

You may perform any number of operations (including zero). In one operation, you may choose an index i such that 0 <= i < n - 1, where s[i] = '0', and s[i + 1] = '1', and swap these two characters.

Return an integer denoting the maximum possible score you can achieve.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

class Solution {
public:
long long maximumScore(vector<int>& nums, string s) {
priority_queue<int> notSelected;
long long res = 0;
for(int i = 0; i < nums.size(); i++) {
notSelected.push(nums[i]);
if(s[i] == '1') {
res += notSelected.top(); notSelected.pop();
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/maximum-score-after-binary-swaps/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.