Description
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?
Input
The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.
Output
Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.
Sample Input
Input
2 4
3 7
Output
8
Input
4 10
4 3 2 1
Output
10
Input
4 10
4 2 3 1
Output
15
题意:就是买股票,低买,高卖,只能买一次,卖一次,想办法赚的钱多。
两种方法,直接暴力和加一点优化
给一下代码:
第一种 直接暴力:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
int n, b, a[2000], maxx, flag, t, k, mm[2000], j;
while(~scanf("%d %d", &n, &b))
{
memset(mm, 0, sizeof(mm));
maxx = flag = t = k = j = 0;
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for(int i = 0; i < n - 1; i++)
{
t = b / a[i];
for(int j = i + 1; j < n; j++)
{
k = max(k, a[j] * t + b - t * a[i]);
}
}
if(b > k) printf("%d\n", b);
else printf("%d\n", k);
}
return 0;
}
第二种 优化
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
int n, b, a[2000], maxx, flag, t, k, mm[2000], j;
while(~scanf("%d %d", &n, &b))
{
memset(mm, 0, sizeof(mm));
maxx = flag = t = k = j = 0;
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for(int i = 0; i < n - 1; i++)
{
if(a[i] < a[i + 1])
{
t = b / a[i];
flag = 2, maxx = 0; //注意每一次都要初始化
for(int j = i + 1; j < n; j++)
maxx = max(maxx, a[j]);
k= max( maxx * t + (b - a[i] * t), k);
}
}
if(!flag) printf("%d\n", b);
else printf("%d\n", k);
}
return 0;
}
第二种方法有bug,就是maxx的初始化问题,开始没有初始化,所以一直WA,加一个初始化就AC了,呵呵呵,这也是大问题啊!