1007. Maximum Subsequence Sum (25)

简介: 简析:求最大子列和,并输出其首末元素。在线处理,关键在于求首末元素。本题囧,16年9月做出来过,现在15分钟只能拿到22分,有一个测试点过不了。

简析:求最大子列和,并输出其首末元素。在线处理,关键在于求首末元素。

本题囧,16年9月做出来过,现在15分钟只能拿到22分,有一个测试点过不了。所以现在的答案是当时的。

#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {
    int n, N = 0, sum = 0, maxsum = 0;
    cin >> n;
    int a[n];
    
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        if(a[i] < 0){
            N++;
        }
    }
    
    int cnt = 0, l = 0, r = 0;
    for (int i = 0; i < n; i++) {
        sum += a[i];
        cnt++;
        if (sum < 0) {
            sum = 0;
            cnt = 0;
        }
        if (sum > maxsum) {
            maxsum = sum;
            l = a[i-cnt+1];
            r = a[i];
        }
    }
    
    if (n == N) {
        l = a[0]; r = a[n-1];
    }
    
    cout << maxsum << ' ' << l << ' ' << r << endl;
    
    return 0;
}


目录
相关文章
|
9月前
|
人工智能 算法
1305:Maximum sum
1305:Maximum sum
LeetCode 209. Minimum Size Subarray Sum
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。
86 0
LeetCode 209. Minimum Size Subarray Sum
LeetCode 64. Minimum Path Sum
给定m x n网格填充非负数,找到从左上到右下的路径,这最小化了沿其路径的所有数字的总和。 注意:您只能在任何时间点向下或向右移动。
68 0
LeetCode 64. Minimum Path Sum
Maximum Subsequence Sum
最大连续子列和问题,在此给出题解 (浙大PTA https://pintia.cn/problem-sets/16/problems/665)
LeetCode之Max Consecutive Ones
LeetCode之Max Consecutive Ones
114 0
1104. Sum of Number Segments (20) consecutive subsequence 每个数出现的次数
Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence.
938 0
[LeetCode]--64. Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or
1078 0
[LeetCode] Maximum Subarray Sum
Dynamic Programming There is a nice introduction to the DP algorithm in this Wikipedia article. The idea is to maintain a running maximum smax and a current summation sum.
878 0