Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
Input: nums = [2,1,5,2,3], s = "01010"
Output: 7
Explanation:
We can perform the following swaps:
i = 0: "01010" changes to "10010"i = 2: "10010" changes to "10100"Positions 0 and 2 contain '1', contributing nums[0] + nums[2] = 2 + 5 = 7. This is maximum score achievable.
Example 2:
Input: nums = [4,7,2,9], s = "0000"
Output: 0
Explanation:
There are no '1' characters in s, so no swaps can be performed. The score remains 0.
Constraints:
n == nums.length == s.length1 <= n <= 1051 <= nums[i] <= 109s[i] is either '0' or '1'Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[2,1,5,2,3] "01010"
[4,7,2,9] "0000"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3781: Maximum Score After Binary Swaps
class Solution {
public long maximumScore(int[] nums, String s) {
long ans = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < nums.length; i++) {
int x = nums[i];
char c = s.charAt(i);
pq.offer(x);
if (c == '1') {
ans += pq.poll();
}
}
return ans;
}
}
// Accepted solution for LeetCode #3781: Maximum Score After Binary Swaps
func maximumScore(nums []int, s string) int64 {
var ans int64
pq := &hp{}
heap.Init(pq)
for i, x := range nums {
pq.push(x)
if s[i] == '1' {
ans += int64(pq.pop())
}
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
func (h *hp) push(v int) { heap.Push(h, v) }
func (h *hp) pop() int { return heap.Pop(h).(int) }
# Accepted solution for LeetCode #3781: Maximum Score After Binary Swaps
class Solution:
def maximumScore(self, nums: List[int], s: str) -> int:
ans = 0
pq = []
for x, c in zip(nums, s):
heappush(pq, -x)
if c == "1":
ans -= heappop(pq)
return ans
// Accepted solution for LeetCode #3781: Maximum Score After Binary Swaps
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3781: Maximum Score After Binary Swaps
// class Solution {
// public long maximumScore(int[] nums, String s) {
// long ans = 0;
// PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
// for (int i = 0; i < nums.length; i++) {
// int x = nums[i];
// char c = s.charAt(i);
// pq.offer(x);
// if (c == '1') {
// ans += pq.poll();
// }
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3781: Maximum Score After Binary Swaps
function maximumScore(nums: number[], s: string): number {
let ans = 0;
const pq = new MaxPriorityQueue<number>();
for (let i = 0; i < nums.length; i++) {
const x = nums[i];
const c = s[i];
pq.enqueue(x);
if (c === '1') {
ans += pq.dequeue()!;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.