So I was recentlr solving a codeforces question and came across this code:
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define pb push_back
#define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL));
using namespace std;
int main()
{
fastread();
int n,a[100001];
ll sum = 0;
int pos = 0,neg = 0,zero = 0,k = 0;
cin>>n;
for(int i=0; i<n; i++){
cin>>a[i];
}
//sort(a,a+n);
for(int i=0; i<n; i++){
if(a[i] == 1 || a[i] == -1)continue;
else if(a[i] < -1){
sum += abs(a[i] + 1);
a[i] -= (a[i] + 1);
}
else if( a[i] > 1){
sum += a[i] - 1;
a[i] = 1;
}
}
for(int i=0; i<n; i++){
if(a[i] == 0){
zero++;
a[i] = 1;
}
else if(a[i] == -1)neg++;
else if(a[i] == 1)pos++;
}
sum += zero;
pos += zero;
//zero = 0;
if(neg % 2 == 1){
if(zero > 0)pos--;
else sum+=2;
}
cout<<sum<<endl;
}
the code runs at about 77 ms, and this was my code:
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define pb push_back
#define fastread() (ios_base:: sync_with_stdio(false),cin.tie(NULL));
using namespace std;
int main()
{
fastread();
int n,m(0),p(1),z(0);
ll ans(0);
cin >> n;
int arr[n];
for(int i = 0; i < n; i++){
cin >> arr[i];
if(arr[i] == 1 || arr[i] == -1){
ans = ans + 0;
}else if(arr[i] == 0){
arr[i] = arr[i]++;
ans++;
//cout << ans << " ";
}else{
if(arr[i] < 0){
ans += abs(arr[i]) - 1;
arr[i] = -1;
//cout << ans << " " << arr[i];
}else{
ans += abs(arr[i]) - 1;
arr[i] = 1;
//cout << ans << " ";
}
}
p = arr[i] * p;
//cout << p << endl;
}
if(p < 0){
cout << ans + 2;
}else{
cout << ans;
}
}
I wanted to optimize the first code which has two loops so I only used one but my program has an execution time of 78 ms, any reasons why decreasing the loop still resulted in more time consumption.
Umakanth Reddy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
13