Problem · String

Maximum Ones After K Operations

Learn this problem
EasyGoldman Sachs logoGoldman SachsNEW GRADINTERNOA

Problem statement

You are given a binary string s containing only '0' and '1'. You may perform at most k operations.

In one operation:

  1. Choose an index i such that 0 ≤ i < s.length - 1.
  2. Set s[i] = max(s[i], s[i + 1]).

Each operation modifies only one position.

Return the maximum possible number of '1' characters in the final string.

Function

maximumOnes(s: String, k: int) → int

Examples

Example 1

s = "10110"k = 1return = 4

Choose i = 1. The string changes from "10110" to "11110", which contains 4 ones.

Example 2

s = "00011"k = 2return = 4

Use the two operations to propagate a '1' leftward: "00011" becomes "00111" and then "01111". The final string contains 4 ones.

Constraints

  • 1 ≤ s.length ≤ 2 * 10^5
  • 0 ≤ k ≤ s.length
  • s contains only '0' and '1'.

More Goldman Sachs problems

drafts saved locally
public int maximumOnes(String s, int k) {
  // Write your code here
}
s"10110"
k1
expected4
checking account