Rama and Friends
Link to the question : GSHOP
HINT :
We must keep in find the following cases and then solve.
- If number of times we can execute the operation, k, is lesser than the number of negative numbers then we simply multiply the larger negative numbers with -1 and add.
- Else, we multiply all negative numbers with -1 and :
2. Else multiply the smallest number with -1 and the add.
RECOMMENDED QUESTION :
I would like the reader to solve this question after getting an AC in this one !!SOURCE CODE :
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,k;
scanf("%d%d",&n,&k);
int count_n=0,count_z=0,count_p=0,i;
long long sum=0,min=9999999,temp;
int a[n+9];
for(i=0;i<n;i++){
scanf("%d",&a[i]);
temp=a[i]>0?a[i]:-1*a[i];
if(temp<min)
min=temp;
if(a[i]<0)
count_n++;
}
if(k<=count_n)
{
int j=0;
for(i=0;i<n;i++)
if(a[i]<0 && j<k)
{
a[i]=-a[i];
j++;
}
for(i=0;i<n;i++)
sum+=a[i];
printf("%lld\n",sum);
}
else
{
for(i=0;i<count_n;i++)
a[i]=-a[i];
for(i=0;i<n;i++){
sum+=a[i];
}
if((k-count_n)%2!=0)
sum+=-(2*min);
printf("%lld\n",sum);
}
}
return 0;
}
could you please tell me why does this not work....its basically the same logic
ReplyDelete#include
#include
#include
using namespace std;
int main(){
int T,n,k;
cin>>T;
while(T--){
cin>>n>>k;
int a[n],i;
for(i=0;i>a[i];
}
i=0;
while(i0&&a[i]<0){
a[i]*=(-1);
k--;
i++;
}
sort(a,a+n);
long long sum=0;
if(k>0)k=k%2;
if(k==1)a[0]*=a[0];
for(i=0;i<n;i++)sum+=a[i];
cout<<sum;
}
return 0;
}
It would be better if you write your code in ideone and send me the link.
ReplyDelete