18708 最大子段和

思路

为了找到一个整数序列中连续且非空的一段使得这段和最大,我们可以使用**Kadane's Algorithm**。该算法的时间复杂度为O(N),适合处理大规模数据。

具体步骤如下:

  1. 初始化两个变量:`max_current`和`max_global`,都设置为序列的第一个元素。

  2. 从第二个元素开始遍历序列,对于每个元素`ai`:

  • 更新`max_current`为`max(ai, max_current + ai)`。

  • 更新`max_global`为`max(max_global, max_current)`。

  1. 最终`max_global`即为所求的最大子段和。

伪代码

```

function find_max_subarray_sum(arr, n):

max_current = arr0

max_global = arr0

for i from 1 to n-1:

max_current = max(arri, max_current + arri)

max_global = max(max_global, max_current)

return max_global

```

C++代码

cpp 复制代码
#include <cstdio>
#include <algorithm>

int find_max_subarray_sum(int arr[], int n) {
    int max_current = arr[0];
    int max_global = arr[0];

    for (int i = 1; i < n; ++i) {
        max_current = std::max(arr[i], max_current + arr[i]);
        max_global = std::max(max_global, max_current);
    }

    return max_global;
}

int main() {
    int n;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; ++i) {
        scanf("%d", &arr[i]);
    }

    int result = find_max_subarray_sum(arr, n);
    printf("%d\n", result);

    return 0;
}

总结

通过使用Kadane's Algorithm,我们可以在O(N)的时间复杂度内找到最大子段和。该算法通过动态更新当前子段和和全局最大子段和,确保在遍历完数组后得到正确的结果。使用`scanf`和`printf`可以提高输入输出的效率,适合处理大规模数据。

相关推荐
罗超驿10 分钟前
15.LeetCode 30. 串联所有单词的子串(Java):滑动窗口+哈希表详解
算法·leetcode
Marianne Qiqi10 分钟前
非hot100的力扣算法题
数据结构·算法·leetcode
thisiszdy15 分钟前
<C++> 智能指针
开发语言·c++
CC数学建模25 分钟前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
玖玥拾28 分钟前
C/C++ 基础笔记(五)
c语言·c++·指针
Dillon Dong28 分钟前
【风电控制】双馈风机网侧高低穿控制策略——从VrtCal信号处理到状态机逻辑的完整解析
算法·变流器·风电控制·dfig
下午写HelloWorld28 分钟前
同态加密(Homomorphic Encryption, HE)
人工智能·算法·密码学·同态加密
CC数学建模29 分钟前
2026第八届中青杯全国大学生数学建模竞赛B题:AI生成内容的质量评估与参数优化完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
sheeta199830 分钟前
LeetCode 每日一题笔记 日期:2026.06.04 题目:3751. 范围内总波动值 I
笔记·算法·leetcode
Flash.kkl38 分钟前
C++基于websocketpp的多用户网页五子棋项目
开发语言·网络·数据库·c++·websocket·mysql