非连续元素的最大总和 [英] Maximum sum of non consecutive elements

查看:27
本文介绍了非连续元素的最大总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个正整数数组,从这个数组中找出非连续元素的最有效算法是什么?

Given an array of positive integers, what's the most efficient algorithm to find non-consecutive elements from this array which, when added together, produce the maximum sum?

推荐答案

动态编程?给定一个数组 A[0..n],让 M(i) 成为使用索引为 0..i 的元素的最优解.然后M(-1) = 0(在循环中使用),M(0) = A[0]M(i) = max(M(i - 1), M(i - 2) + A[i]) 对于 i = 1, ..., n.M(n) 就是我们想要的解决方案.这是 O(n).您可以使用另一个数组来存储为每个子问题做出的选择,从而恢复实际选择的元素.

Dynamic programming? Given an array A[0..n], let M(i) be the optimal solution using the elements with indices 0..i. Then M(-1) = 0 (used in the recurrence), M(0) = A[0], and M(i) = max(M(i - 1), M(i - 2) + A[i]) for i = 1, ..., n. M(n) is the solution we want. This is O(n). You can use another array to store which choice is made for each subproblem, and so recover the actual elements chosen.

这篇关于非连续元素的最大总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆