Codeforces 797B - Odd sum

本文介绍了一道 CodeForces 上的题目 B.Oddsum 的解题思路及实现代码。题目要求找到一个整数序列中具有最大奇数和的子序列。文章详细解释了解决方案,并附上了 C++ 实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
题目大意:求最大奇数和的子序列的和。
方法:先将正数加起来,得sum
    如果sum为奇数,输出sum;
    否则,sum1=sum-最小正奇数,sum2=sum+最大负奇数,输出max(sum1,sum2)。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<iostream>
#define ll long long
using namespace std;
const int N=1e5;
int a[N];
int temp1=-1e5,temp2=1e5; 
int main()
{
        int n;
        int sum=0;
        int index1=-1,index2=-1;
        int sum1=-0x7f7f7f7f,sum2=-0x7f7f7f7f;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            if(a[i]>0)
            {
                sum+=a[i];
                if(a[i]%2)
                {
                    temp2=min(temp2,a[i]);
                }
            }
            else if(a[i]<0)
            {
                if(a[i]%2)
                temp1=max(temp1,a[i]);
            }
        }
            if(sum%2)cout<<sum<<endl;
            else
            {
                    sum1=sum-temp2;
                    sum2=sum+temp1;
                cout<<max(sum1,sum2)<<endl;
            }
            return 0;
}

有点乱,我是输入的时候就找最大负奇数和最小正奇数的。

转载于:https://www.cnblogs.com/widsom/p/6720400.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值