262B - Roma and Changing Signs - CodeForces Solution


greedy *1200

Please click on ads to support us..

Python Code:

n, changes = map(int, input().split())
incomes = sorted(list(map(int, input().split())))

diff = 0

i = 0
while i < len(incomes) and incomes[i] <= 0 and changes > 0 :
    diff += (incomes[i] * -2)
    changes -= 1
    i += 1

if changes % 2 == 1:
    diff -= abs(sorted(incomes, key=lambda l: abs(l))[0]) * 2
print(sum(incomes) + diff)

C++ Code:

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

int main()
{ios_base::sync_with_stdio(false);
    cin.tie(NULL);
int x,m;
cin>>x>>m;
int arr[x];
for(int i=0;i<x;i++){
    cin>>arr[i];
}
int count=0;
ll sum=0;
bool flag=0,cn;
sort(arr,arr+x);
    int mx=1e9,idx;
        for(int i=0;i<x;i++){
            if(arr[i]<0&&count!=m){
                arr[i]*=-1;
                count++;
            }
        if(mx>arr[i]){
            mx=arr[i];
            idx=i;
            //cout<<idx;
            }
            //cout<<arr[i]<<" ";
        }

        if((m-count)%2){
                arr[idx]*=-1;
        }
    for(int i=0;i<x;i++){
        sum+=arr[i];
    }



cout<<sum;

}




Comments

Submit
0 Comments
More Questions

452A - Eevee
1647B - Madoka and the Elegant Gift
1408A - Circle Coloring
766B - Mahmoud and a Triangle
1618C - Paint the Array
469A - I Wanna Be the Guy
1294A - Collecting Coins
1227A - Math Problem
349A - Cinema Line
47A - Triangular numbers
1516B - AGAGA XOOORRR
1515A - Phoenix and Gold
1515B - Phoenix and Puzzle
155A - I_love_username
49A - Sleuth
1541A - Pretty Permutations
1632C - Strange Test
673A - Bear and Game
276A - Lunch Rush
1205A - Almost Equal
1020B - Badge
1353A - Most Unstable Array
770A - New Password
1646B - Quality vs Quantity
80A - Panoramix's Prediction
1354B - Ternary String
122B - Lucky Substring
266B - Queue at the School
1490A - Dense Array
1650B - DIV + MOD