不相邻的最大子数组和

不相邻的最大子数组和

问题描述

给一个数组,数组元素为不小于零,求和最大的子数组,其中每个元素在原数组中不相邻。

解题思路

刚拿到题目可能隐约觉得是个dp问题,求前i个元素的最大子数组和,但还是有点手足无措,关键是将问题分情况讨论:前i个元素的最大子数组包含第i个元素和不包含第i个元素。

  1. 包含第i个元素,则一定不能包含第i-1个元素,包含第i个元素的最大子数组为不包含第i-1个元素的最大子数组和加上第i个元素
  2. 不包含第i个元素,则前i个元素的最大子数组和就是前i-1个元素的最大子数组和

设包含第i个元素的最大子数组和为dp[i],不包含第i个元素的最大子数组和为np[i],前i个元素的最大子数组和为max(dp[i], np[i]),根据上面的分析,则有如下推导公式:

  • dp[i] = np[i-1]+arr[i]
  • np[i] = max(np[i-1], dp[i-1])

代码

#include <stdio.h>
#include <stdlib.h>

/*
Problem description:
Find the max sub sum in the arr that each element doesn't neighbor each other.
Elements in the array are not less than 0.
*/

int max_sub_sum(int* arr, int len){
    if(len<0)
    {
        printf("error: array length is less than 0!\n");
        return -1;
    }
    int result = 0;
    /*
    dp[i]: max sub sum that includes the element i
    */
    int* dp = (int*)malloc(sizeof(*dp)*len);

    /*
    np[i]: max sub sum that excludes the element i
    */
    int* np = (int*)malloc(sizeof(*np)*len);

    /*
    This is a dp problem.
    If we use arr[i] to get the result, then we cannot use arr[i-1].
    so we get:
    dp[i] = np[i-1]+arr[i]

    If we don't use arr[i] to get the result, then we the ith max sub sum
    equals the (i-1)th max sub sum, for we don't care about whether it includes
    arr[i].
    so we get:
    np[i] = max(dp[i-1], np[i-1])

    Time complexity is O(n).
    */
    dp[0] = arr[0];
    np[0] = 0;

    int i=0;
    for(i=1; i<len; i++){
        dp[i] = np[i-1] + arr[i];
        np[i] = dp[i-1]>np[i-1] ? dp[i-1] : np[i-1];

    }

    result = dp[len-1]>np[len-1] ? dp[len-1] : np[len-1];

    free(dp);
    free(np);
    return result;
}

int main()
{
    int arr[8] = {1, 7, 4, 0, 9, 4, 8, 8};
    int result = max_sub_sum(arr, 8);

    printf("result: %d\n", result);


    return 0;
}

codeblocks源码链接:
https://github.com/lilingyu/max_sub_sum

ref

http://blog.csdn.net/realxie/article/details/8063885

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值