1749. Maximum Absolute Sum of Any Subarray(DP)

本文介绍了一种更高效的方法来解决计算数组中最大绝对区间和的问题,通过利用前缀和计算最小值和最大值,避免了O(N^2)的暴力搜索。解决方案展示了如何通过计算并维护前缀和及更新最小和最大值来实现,时间复杂度降低到线性。
摘要由CSDN通过智能技术生成

Normally, you would try a O(N^2) brute force.

but actually, you know we are finding a interval sum and take a absolute value.

interval sum i, j = prefixsum[j] - prefixsum[i - 1];

so if we want the max interval sum, we need to find the minimum prefixSum and max prefix sum.

so we just need to calculate the prefix sum, and updating the min and max prefixsum, and return their difference.

class Solution {
public:
    int maxAbsoluteSum(vector<int>& A) {
        int s = 0, mi = 0, ma = 0;
        for (int& a: A) {
            s += a;
            mi = min(mi, s);
            ma = max(ma, s);
        }
        return ma - mi;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值