2024.12.25 周三

2024.12.25 周三


Q1. 1100

A subarray is a continuous part of array.

Yarik recently found an array a of n elements and became very interested in finding the maximum sum of a non empty subarray. However, Yarik doesn't like consecutive integers with the same parity, so the subarray he chooses must have alternating parities for adjacent elements.

For example, [1,2,3] is acceptable, but [1,2,4] is not, as 2 and 4 are both even and adjacent.

You need to help Yarik by finding the maximum sum of such a subarray.


------------------------独自思考分割线------------------------

  • 思路好想,实现的时候出了很多问题。

A1.

  1. 首先如果不考虑额外条件。一眼:遍历求前缀和同时维护最小前缀和(不能为空所以是i1的),同时更新答案 pre[i]min_pre
  2. 额外条件是连续子数组不包含连续奇偶性相同的数。简单思考发现以满足额外条件将数组分为多个连续子数组,每个子数组单独计算。即分割后互不干扰/贡献独立。

------------------------代码分割线------------------------

A1.

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

void _();
signed main()
{
   int t=1;cin>>t;
   while(t--) _();
}

void _()
{
    int n;cin>>n;
    vector<int> a(n+1);
    for(int i=1;i<=n;i++) cin>>a[i];
    vector<vector<int>> vec;
    for(int i=1;i<=n;i++)
    {
        vector<int> t{a[i]};
        int j=i+1;
        for(;j<=n&&((abs(a[j])%2)!=(abs(a[j-1])%2));j++) // &1优先级、对负数   负数%2
        t.push_back(a[j]);
        vec.push_back(t);
        i=j-1;
    }
    int res=-1e12;
    for(auto a:vec)
    {
        // for(auto v:a) cout<<v<<' ';cout<<endl;
        int ans=0; 
        res=max(res,a[0]);
        if(a.size()>1)
        {
            ans=min(ans,a[0]);
            int pre=a[0];
            for(int i=1;i<a.size();i++)
            {  ans=min(ans,pre);
                pre+=a[i]; 
                res=max(res,pre-ans);
              
            }
        }
    }
    cout<<res<<endl;
}

posted @   Jkke  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示