ACM CodeFest 2.0 - Play with strings Editorial

PROBLEM LINK:

Question Link

Author: return1201

DIFFICULTY:

EASY

PREREQUISITES:

Brute Force, Kadane’s Algo

PROBLEM:

Play with strings | Codechef

EXPLANATION:

There are at most 6 different ways to assign the values A, B, C to numeric 0,1,2. Each of these assignments will result in the formation of a different Sequence.

After we have formed a sequence we need to find the Maximum sum contiguous sequence of the formed sequence, which can be found using Kadane’s Algorithm.

Time complexity: O(n)

SOLUTIONS:

Setter's Solution
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define pb push_back
#define pf push_front
#define all(t) t.begin(), t.end()
#define inrange(i, a, b) (((i)>= min((a), (b))) && ((i) <= max((a), (b))))
typedef vector<ll> vi;
typedef pair<ll, ll> pii;
#define fi first
#define se second
#define upb upper_bound
#define lwb lower_bound 
#define show(x) cout << #x << " is " << x << "\n";
const ll inf = 2e18;
const ll mod = 1e9 + 7;
const ld pi = 3.141592653589793238462643383279502884;
 
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
 
void print(ll a[], ll n){for(ll i=0;i<n;i++){cout<<a[i]<<" ";}cout<<"\n";}
ll power(ll x, ll y){
    if(y<=0) return 1;
    ll ans = 1;
    x %= mod;
    while(y){
        if(y&1)
            ans = (x * ans) % mod;
        x = (x * x) % mod;
        y >>= 1;
    }
    return ans;
}
ll modInverse(ll n) {return power(n, mod-2);}
inline ll mul(ll a, ll b){ return (a * b) % mod; }
inline ll sub(ll a, ll b){ ll c = (a - b); if(c < 0) c += mod; return c; }
inline ll add(ll a, ll b){ ll c = (a + b); if(c >= mod) c -= mod; return c; }
inline ll divi(ll a, ll b){ return mul(a, modInverse(b)); }
 
//------------------------------------------------------------------------------------------
 
//const ll N = 2e5 + 1;
//vector<ll> adj[N];
//bool visited[N];
 
ll kadane(ll a[], ll n){
    ll ma = -inf;
    ll sum = 0;
 
    for(int i=0;i<n;i++){
        sum = sum + a[i];
        ma = max(ma, sum);
        sum = max(0ll, sum);
    }
 
    return ma;
}
 
int main() {
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
 
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    cout<<fixed<<setprecision(10);
 
    ll n;
    cin>>n;
    ll a[3];
    int numeric[3];
    for(int i=0;i<3;i++){
        cin>>a[i];
        numeric[i] = i;
    }
    string s;
    cin>>s;
    ll ans=0;
    do{
        ll b[n];
        for(int i=0;i<n;i++){
            int ch = s[i]-'a';
            b[i] = a[numeric[ch%3]];
        }
        ans = max(ans, kadane(b, n));
    }
    while(next_permutation(numeric, numeric+3));
 
    cout<<ans;
 
    return 0;
}