不相邻的最大子数组和
问题描述
给一个数组,数组元素为不小于零,求和最大的子数组,其中每个元素在原数组中不相邻。
解题思路
刚拿到题目可能隐约觉得是个dp问题,求前i个元素的最大子数组和,但还是有点手足无措,关键是将问题分情况讨论:前i个元素的最大子数组包含第i个元素和不包含第i个元素。
- 包含第i个元素,则一定不能包含第i-1个元素,包含第i个元素的最大子数组为不包含第i-1个元素的最大子数组和加上第i个元素
- 不包含第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