Maximum Sum of All Sub-arrays

参考:http://codercareer.blogspot.com/2011/09/no-03-maximum-sum-of-all-sub-arrays.html

Question: A sub-array has one number of some continuous numbers. Given an integer array with positive numbers and negative numbers, get the maximum sum of all sub-arrays. Time complexity should be O(n).

For example, in the array  { 1, -2, 3, 10, -4, 7, 2, -5 }, its sub-array { 3, 10, -4, 7, 2 } has the maximum sum 18

解过一次这道题,再做的时候又忘记怎么做了,想想还是因为思路不够清晰,对问题理解得不够透彻。

最关键是理解:哪些是有可能是解的子数组。

有可能是解的子数组:
{1}
{1, -2}  ----> 如何理解这个有可能是解呢?
{3}   ---> 1, -2, 3 不可能是解,因为1 + -2已经是负数了,但为什么{1, -2}还是要考虑呢?
{3, 10}
{3, 10, -4}
{3, 10, -4, 7}
{3, 10, -4, 7, 2}
{3, 10, -4, 7, 2, -5}


#include <stdio.h>

int max_sub_array(int data[], int n)
{
        int max_sum;
        int sum;
        int i;

        max_sum = sum = data[0];
        for (i = 1; i < n; i++) {
                sum += data[i];

                if (sum > max_sum)
                        max_sum = sum;
                if (sum < 0)
                        sum = 0;
        }

        return max_sum;
}

int main()
{
        int data[] =  {1, -2, 3, 10, -4, 7, 2, -5};
        int n = 8;

        printf("%d\n", max_sub_array(data, n));

        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值