2024/4/2—力扣—连续数列

代码实现:

思路:最大子数组和

**解法一:**动态规划

cpp 复制代码
#define max(a, b) ((a) > (b) ? (a) : (b))

int maxSubArray(int* nums, int numsSize) {
    if (numsSize == 0) { // 特殊情况
        return 0;
    }
    int dp[numsSize];
    dp[0] = nums[0];
    int result = dp[0];
    for (int i = 1; i < numsSize; i++) {
        dp[i] = max(dp[i - 1] + nums[i], nums[i]); // 状态转移方程
        result = max(result, dp[i]); // result 保存dp[i]的最大值
    }
    return result;
}

**解法二:**贪心

cpp 复制代码
int maxSubArray(int *nums, int numsSize) {
    int result = INT32_MIN;
    int count = 0;
    for (int i = 0; i < numsSize; i++) {
        count += nums[i];
        if (count > result) { // 取区间累计的最大值(相当于不断确定最大子序终止位置)
            result = count;
        }
        if (count <= 0) {
            count = 0; // 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和
        }
    }
    return result;
}
相关推荐
py有趣12 小时前
力扣热门100题之合并区间
算法·leetcode
派大星~课堂12 小时前
【力扣-138. 随机链表的复制 ✨】Python笔记
python·leetcode·链表
py有趣12 小时前
力扣热门100题之最小覆盖子串
算法·leetcode
北顾笙98013 小时前
day15-数据结构力扣
数据结构·算法·leetcode
人道领域14 小时前
【LeetCode刷题日记:24】两两交换链表
算法·leetcode·链表
北顾笙98014 小时前
day16-数据结构力扣
数据结构·算法·leetcode
wsoz14 小时前
Leetcode子串-day4
c++·算法·leetcode
会编程的土豆14 小时前
【数据结构与算法】二叉树大总结
数据结构·算法·leetcode
y = xⁿ15 小时前
【LeetCode Hot100】动态规划:T70:爬楼梯 T118:杨辉三角形 T198:打家劫舍
算法·leetcode·动态规划
人道领域15 小时前
【LeetCode 刷题日】19.删除链表的倒数第n个节点
算法·leetcode·链表