codeforces 797B

B. Odd sum

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.

Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

You should write a program which finds sum of the best subsequence.

Input

The first line contains integer number n (1 ≤ n ≤ 105).

The second line contains n integer numbers a1, a2, ..., an ( - 104 ≤ ai ≤ 104). The sequence contains at least one subsequence with odd sum.

Output

Print sum of resulting subseqeuence.

Examples
input
4
-2 2 -3 1
output
3
input
3
2 -5 -3
output
-1
Note

In the first example sum of the second and the fourth elements is 3.

 

 解题思路:

题意为求最大的和为奇数的子序列

那么先将所有正数加起来,如果和是奇数那就是最大的奇数和,如果是偶数的话,就要把它变为奇数

有两种情况:

1.减去最小的正奇数

2.加上最大的负奇数

最后判断一下两种情况的大小,取较大值

实现代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int m,a[100005],b[100005],c[100005];
    int i;
    cin>>m;
    int k = 0,l= 0;
    for(i=0;i<m;i++)
    {
        cin>>a[i];
        if(a[i]>0)
            b[k++] = a[i];
        else
            c[l++] = a[i];
    }
    sort(b,b+k);
    int sum = 0;
    for(i=k-1;i>=0;i--)
    {
        sum += b[i];
    }
    if(sum%2==0)
    {
        int sum1=sum,sum2=sum;
        sum = -99999999;
        for(i=0;i<k;i++)
        {
            if(b[i]%2==1)
            sum1-=b[i];
            if(abs(sum1)%2==1){
                sum = sum1;
                break;
            }
               }
            //cout<<"sum1:"<<sum1<<endl;
        sort(c,c+l);
        for(i=l-1;i>=0;i--){
            if(abs(c[i])%2==1)
                sum2+=c[i];
            if(abs(sum2)%2==1){
                sum = max(sum,sum2);
            }
        }
         //cout<<"sum2:"<<sum2<<endl;
    }
    cout<<sum<<endl;
}

 

 

转载于:https://www.cnblogs.com/kls123/p/6817299.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值