不相邻的最大子数组和
来源:互联网 发布:手机简谱编曲软件 编辑:程序博客网 时间:2024/05/16 05:56
不相邻的最大子数组和
问题描述
给一个数组,数组元素为不小于零,求和最大的子数组,其中每个元素在原数组中不相邻。
解题思路
刚拿到题目可能隐约觉得是个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
ref
http://blog.csdn.net/realxie/article/details/8063885
0 0
- 不相邻的最大子数组和
- 动态规划求不相邻的最大子数组和
- 动态规划求不相邻的最大子数组和
- 动态规划求不相邻的最大子数组和
- 求不相邻的最大子数组和
- 找出数组中任何相邻子向量的最大和
- 元素互不相邻的最大和子数组
- 不相邻子序列最大和
- House Robber I - 由数组中不相邻元素组成的子数组,使其和最大
- 数组中不相邻元素的最大和
- [LeetCode] House Robber 求数组中元素两两不相邻的子序列最大和
- [LeetCode] House Robber II 求循环数组中元素两两不相邻的子序列最大和
- 给定一个非负数组,求不相邻元素的最大和。
- 找出两个不相交连续子数组的最大和
- 不相交最大子数组和
- 子数组的最大和
- 子数组的最大和
- 子数组的最大和
- C++ 走向远洋——44(项目一、点—圆—圆柱类族的设计、派生类)
- android 6.0 textview 跑马灯失效和出现抖动的解决方法
- Html+CSS CSS中的选择器
- Ubuntu 16.04 系统安装
- C++ 游泳池造价
- 不相邻的最大子数组和
- Retrofit2.0+RxJava+MVP+Bmob的使用
- 初识-常见浏览器兼容性问题与解决方案
- SpringMvc+quartz
- leetcode 181. Employees Earning More Than Their Managers
- 通用菜单
- 数对之差的最大值
- 安卓_登录界面短信验证码
- uva 10340 - All in All