算法——Coin-row problem(币值最大化问题)

题目描述

There is a row of n coins whose values are some positive integers c₁, c₂,...,cn, not necessarily distinct. The goal is to pick up the maximum amount of money subject to the constraint that no two coins adjacent in the initial row can be picked up.

翻译

给定一排n个硬币,其面值均为正整数c1,c2,...,cn,这些数并不一定两两相同。请问如何选择硬币,使得在其原始位置互不相邻的条件下,所选的总金额最大。 

输入

Two lines, the first line is n (0< n <=10000), and the second line is value of coin(0< value <= 2^32).

输出

the maximum amount of money.

样例输入

6
5 1 2 10 6 2

样例输出

17

代码 

#include<iostream>
using namespace std;
int a[10000];
int main(){
	int n;
	cin>>n;
	a[0]=0;
	for(int i = 1; i <= n; i++){
		cin>>a[i];
		a[i] = max(a[i-2] + a[i],a[i-1]);
		
	}
	cout<<a[n]<<endl;
	return 0;
}

思路 

 符合初始条件的递归方程:

画图会更加的明白:

把图上的过程看懂了,这道题就会变得特别简单。 

发布了18 篇原创文章 · 获赞 224 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45703420/article/details/105416335
今日推荐