Maximize your Balance#11860

Maximize your Balance (Çözgüdiň düşündirişi)

Problem Author:

TheSensei

Prepared by:

Hasan Saleh (MathModel)

Edited by:

Hasan Saleh (MathModel)

Solution Our goal is to maximize the value of the expression notice that for each with s_i=\mathtt{B} then it contributes with -a_i to expression and s_i=\mathtt{S} (Sell) contributes with a_i to sum , thus we want to maximize the values of and minimize values of , We've exactly two cases :

  1. We've s_i=\mathtt{B} for all or s_i=\mathtt{S} for all , which implies that we cannot do any useful swap , so we calculate the expression as it's

  2. We've both and appears in , then we want to reduce the max value of a_i with s_i=\mathtt{B} because it's contributes with negative value , A greedy approach is to swap the max value of a_i with s_i=\mathtt{B} with min value of a_i of thus we've a larger sum and this is the best solution.

#include<bits/stdc++.h>
#define int long long
using namespace std;

void solve(){
    int n;cin>>n;
    string s;cin>>s;
    vector<int>a(n);
    for(auto &i:a)cin>>i;
    int mx=0;
    int mn=1e18;
    int idx1=-1,idx2=-1;
    for(int i=0;i<n;i++){
        if(s[i]=='B'){
            if(a[i]>mx){
                idx1=i;
                mx=a[i];
            }
        }
        if(s[i]=='S'){
            if(a[i]<mn){
                idx2=i;
                mn=a[i];
            }
        }
    }
    if(idx1!=-1 && idx2!=-1){
        swap(s[idx1],s[idx2]);
    }
    int ans=0;
    for(int i=0;i<n;i++){
        if(s[i]=='B'){
            ans+=a[i]*-1;
        }else{
            ans+=a[i];
        }
    }
    cout<<ans<<"\n";
}

signed main(){
    int t;cin>>t;
    while(t--){
        solve(); 
    }
    return 0;
}

Complexity