algorithm - 最大和序列使得没有两个元素是相邻的
问题描述
我的最大和实现如下,但我需要给出最大和的序列google
,stackoverflow
但没有输出序列。
public int maxSum(int arr[]) {
int excl = 0;
int incl = arr[0];
for (int i = 1; i < arr.length; i++) {
int temp = incl;
incl = Math.max(excl + arr[i], incl);
excl = temp;
}
return incl;
}
所以 3 2 7 10 应该返回 (3 and 10) 或 3 2 5 10 7 应该返回 (3, 5 and 7) 或者 {5, 5, 10, 100, 10, 5} 将返回 (5, 100 and 5)或 {1, 20, 3} 将返回 20 我完全想要这个问题的解决方案,但我需要的返回值是包含在最大总和而不是最大总和值中的元素序列
解决方案
看起来类似于最长增加片段问题(自上而下的方法)。您可以返回它的总和,而不是序列的长度。此外,不要跳过一个,而是跳过两个以避免相邻的元素。
推荐阅读
- r - 如何根据其他元素并行修改向量的元素?
- python - 如何让我的程序重置并添加将自动重新启动的继续提示重新启动程序
- php - PHP 测试脚本有效,其他脚本中的相同代码无效
- java - IBM MQ SSL 连接问题
- python - 使用 SVM 的 coef_ 函数的特征重要性
- python - Kivy 屏幕管理器无法在屏幕之间切换
- firebase - 执行 Firebase 规则时遇到问题
- javascript - Javascript 和 Django Rest Framework - 无法读取属性
- spring-boot - JdbcBatchItemWriter - setSql - 如何修复时间戳类型不匹配
- javascript - 在 nodejs 中操作 html 文档服务器端?