算法——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;
}

 

思路 

 符合初始條件的遞歸方程:

畫圖會更加的明白:

把圖上的過程看懂了,這道題就會變得特別簡單。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章