# PHSHFT - Editorial

**URL:** <https://discuss.codechef.com/t/phshft-editorial/126104>\
**Category:** editorial\
**Tags:** editorial, greedy, prefix-sum, start262\
**Created:** [October 28, 2026, 5:30pm UTC](https://discuss.codechef.com/t/phshft-editorial/126104 "2026-10-28T17:30:16Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![iceknight1093](https://www.codechef.com/sites/all/themes/abessive/images/user_default_thumb.jpg) [@iceknight1093](https://discuss.codechef.com/u/iceknight1093)\
**Post date:** [October 28, 2026, 5:30pm UTC](https://discuss.codechef.com/t/phshft-editorial/126104/1 "2026-10-28T17:30:16Z")

</div>

# PROBLEM LINK:

[Practice](https://www.codechef.com/problems/PHSHFT)  
[Contest: Division 1](https://www.codechef.com/START262A/problems/PHSHFT)  
[Contest: Division 2](https://www.codechef.com/START262B/problems/PHSHFT)  
[Contest: Division 3](https://www.codechef.com/START262C/problems/PHSHFT)  
[Contest: Division 4](https://www.codechef.com/START262D/problems/PHSHFT)

_ **Author:** _ [nikhil\_010309](https://www.codechef.com/users/nikhil_010309)  
_ **Tester:** _ [raysh07](https://www.codechef.com/users/raysh07)  
_ **Editorialist:** _ [iceknight1093](https://www.codechef.com/users/iceknight1093)

# DIFFICULTY:

TBD

# PREREQUISITES:

Prefix sums

# PROBLEM:

You have a binary string S.  
You can choose an index i such that S\_{i-1} \ne S\_{i+1}, and flip S\_i. This has a cost of C\_i.

Find the lexicographically maximum binary string you can reach within a budget of B.

# EXPLANATION:

Let’s define D\_i = S\_i \oplus S\_{i+1} to be the difference between adjacent characters of the string.  
(Recall that we’re assuming S\_0 = S\_{N+1} = 0, so D\_0 and D\_N are well-defined.)

Observe that the condition S\_{i-1} \ne S\_{i+1} is equivalent to D\_{i-1} \ne D\_i.  
Further, flipping S\_i flips both D\_{i-1} and D\_i, which is equivalent to swapping them.

So, on D, we can swap adjacent elements when they aren’t equal - which is really the same as being able to swap adjacent elements period since there’s no point swapping equal elements when we’re on a budget.

Now, note that the number of ones in D cannot be changed - but we can move them around.  
Further, the string S is determined exactly by the positions of the ones in D, as follows:

- Suppose the ones in D are at positions x\_1, x\_2, \ldots, x\_k
- Then, S will have:
  - Zeros till position x\_1 - 1.
  - Ones from position x\_1 to position x\_2-1.
  - Zeros from position x\_2 to position x\_3-1.
  - And so on.

Basically, the ones in D denote the positions where maximal blocks of equal values in S start.

* * *

With this in mind, to lexicographically maximize S we see that we want:

- x\_1 to be as small as possible (to have a 1 as early as possible)
- x\_2 to be as large as possible (to extend the first block of ones as long as we can)
- x\_3 to be as small as possible (again, to start the next block of ones early)  
\vdots

In general, we want the odd-indexed x\_i to be minimized, while the even-indexed ones must be maximized.  
Of course, this must be done while maintaining x\_1 \lt x\_2 \lt\ldots\lt x\_k at all times.

Let’s now attempt to do this greedily.

Moving x\_1 as far left as possible is easy - we know the cost of each movement, so simply repeat that as much as needed (or possible.)  
Moving x\_2 right is a bit harder - because when doing this, we might end up having to push some other values of x\_i to the right in the meantime.

One way to implement this nicely, is to group the x\_i into contiguous blocks when they occupy contiguous positions.  
Then, when attempting to move a point right, if it’s attached to a block we instead attempt to move the entire block right; because this is the only way to move this point one step.  
The cost of this move is a subarray sum over C and can be computed using prefix sums.

Finally, whenever we are unable to move right further, we simply fix the leftmost element of the block in place, and then detach it from the current block so that the block can move by itself later on.

This simple-looking optimization in fact gives us a linear-time algorithm!

To see why:

- The total number of leftward moves is bounded by N, even making them one at a time.
  - This is because if some x\_i crosses a position moving left, then x\_{i+1} must be to the right of that position - and will remain to its right.
  - Thus, no other x\_j for j \gt i will ever touch this position again.

- Similarly, the total number of rightward moves is bounded by N, because after moving a block rightwards from a position we’ll never touch it with a rightward move ever again.

So, with proper implementation this gives a simple linear-time algorithm!

* * *

There are other solutions as well, where using some prefix sums and binary search you can find all the necessary costs quickly enough; though that’s a bit lengthier to implement and likely more error-prone compared to the method above.  
Nonetheless, such an implementation is attached below for reference.

# TIME COMPLEXITY:

\mathcal{O}(N) or \mathcal{O}(N\log N) per testcase.

# CODE:

> **Tester's code (C++, Nlog N)**
>
> ```cpp
> #include <bits/stdc++.h>
> using namespace std;
> #define int long long
> #define INF (int)1e18
> 
> mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
> 
> void Solve() 
> {
> // for an array (a1, ..., ak) number of 0s before each 1 and (b1, .., bk), cost is sum |ai - bi| 
> // for a partial array, k 0s placed, upto i fixed
>     
> int n, budget; cin >> n >> budget;
> string s; cin >> s;
> s = "0" + s + "0";
>     
> vector <int> c(n + 1);
> for (int i = 1; i <= n; i++){
> cin >> c[i];
> }
>     
> vector <int> t;
> for (int i = 1; i <= n + 1; i++){
> t.push_back((int)(s[i] != s[i - 1]));
> }
>     
> vector <int> b;
> int curr = 0;
> for (auto x : t){
> if (x == 0){
> curr++;
> } else {
> b.push_back(curr);
> }
> }
>     
> if (b.size() == 0){
> for (int i = 1; i <= n; i++){
> cout << "0";
> }
> cout << "\n";
> return;
> }
>     
> int lst = 0;
> string ans = "";
> vector <int> d;
> int lim = 0;
> int base = 0;
>     
> vector <int> pc(n + 1);
> for (int i = 1; i <= n; i++){
> pc[i] = pc[i - 1] + c[i];
> }
>     
> vector <int> ppc(n + 1), pcb(n + 1);
> for (int i = 1; i <= n; i++){
> ppc[i] = ppc[i - 1] + pc[i];
> }
> for (int i = 0; i < b.size(); i++){
> pcb[i] = pc[b[i] + i];
> if (i > 0) pcb[i] += pcb[i - 1];
> }
>     
> auto f = [&](int zero1, int zero2, int ind){
> // go to 1-indexed
> int pos1 = zero1 + ind + 1;
> int pos2 = zero2 + ind + 1;
>         
> // need to go from pos1 to pos2 
> if (pos1 > pos2) swap(pos1, pos2);
>         
> return pc[pos2 - 1] - pc[pos1 - 1];
> };
>     
> auto check = [&](){
> int sz = d.size();
> if (sz > (int)b.size()) return false;
> if (lim > ((int)t.size() - (int)b.size())) return false;
>         
> int cost = base;
> // for (int i = sz; i < b.size(); i++){
> // if (b[i] > lim) continue; // 0 cost 
> // cost += f(lim, b[i], i);
> // }
>         
> int lo = sz, hi = (int)b.size();
> while (lo != hi){
> int mid = (lo + hi) / 2;
> if (b[mid] > lim){
> hi = mid;
> } else {
> lo = mid + 1;
> }
> }
>         
> // i = [sz, lo) 
> // in this range, we want pc[lim + i - 1] - pc[b[i] + i - 1]
> // for (int i = sz; i < lo; i++){
> // cost += pc[lim + i] - pc[b[i] + i];
> // }
>         
> auto get_sum = [&](vector <int> &a, int l, int r){
> if (l == 0){
> return a[r];
> } else {
> return a[r] - a[l - 1];
> }
> };
>         
> cost += get_sum(ppc, lim + sz, lim + lo - 1);
> cost -= get_sum(pcb, sz, lo - 1);
>         
> return cost <= budget;
> };
>     
> auto add0 = [&](){
> lim++;
> };
>     
> auto add1 = [&](){
> d.push_back(lim);
> if (d.size() <= b.size()){
> int sz = d.size();
> base += f(d[sz - 1], b[sz - 1], sz - 1);
> }
> };
>     
> auto rem0 = [&](){
> lim--;
> };  
>     
> auto rem1 = [&](){
> if (d.size() <= b.size()){
> int sz = d.size();
> base -= f(d[sz - 1], b[sz - 1], sz - 1);
> }
> d.pop_back();
> };
>     
> for (int i = 1; i <= n; i++){
> if (lst == 0){
> // try to make 1 work 
> add1();
> if (!check()){
> rem1();
> add0();
> ans += "0";
> lst = 0;
> } else {
> ans += "1";
> lst = 1;
> }
> } else {
> // try to make 0 work 
> add0();
> if (!check()){
> rem0();
> add1();
> ans += "0";
> lst = 0;
> } else {
> ans += "1";
> lst = 1;
> }
> }
> }
>     
> cout << ans << "\n";
> }
> 
> int32_t main() 
> {
> auto begin = std::chrono::high_resolution_clock::now();
> ios_base::sync_with_stdio(0);
> cin.tie(0);
> int t = 1;
> // freopen("in", "r", stdin);
> // freopen("out", "w", stdout);
>     
> cin >> t;
> for(int i = 1; i <= t; i++) 
> {
> //cout << "Case #" << i << ": ";
> Solve();
> }
> auto end = std::chrono::high_resolution_clock::now();
> auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
> cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n"; 
> return 0;
> }
> 
> ```
