您的位置:首页 > 其它

Amazon Hiring Campus 2013

2014-10-09 00:19 295 查看
Let's assume that there is a simple market for beans. Every day there is a published bean price in the market. Traders can buy or sell at the published price. There is a trader who time travelled to future and brought back the price information for a number
of days in the future. If you have this information and you are allowed to buy and sell many times. How do you make the maximum profit? The price information will be given as an array of numbers. Each number is for a day’s trading price. The numbers are all
integers to simplify the problem. You will need to return the index of the buy-in point and sell-out point for maximum profit.

Rules:

1) The input line length less than 1000, and the trading price length less than 100;

2) The trading price is positive integer;

3) The trading prices are delimited by ' '(single space);

4) Please make sure every buying and selling period shortest. especially, please ouput '-' if all the trading prices are the same or no trading point;

Sample Input and Output:

Input 1

1 3 5 4 2 8 10

Output 1

1 3 5 7

To make the maximum profit, you should buy at $1 and sell at $5, and then buy at $5 and sell it at $10. so the output is "1 3 5 7".

Input 2

1 1 1 3 5 4 2 2 2 8 10

Ouput 2

3 5 9 11
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void calculateAndPrint(int array[], int length)
{
//Your Code is here
int min = 0, max = 0, flag = 0, ind = 0, len = 0;
int* temp;
temp = (int*)malloc(length * sizeof(int));
for(int i = 0; i < length; i++)
temp[i] = 0;
min = array[0];
for(int i = 1; i < length; i++)
{
if(flag == 0)
{
if(array[i] <= min)
min = array[i];
else if(array[i] > min)
{
temp[ind] = i;
ind++;
max = array[i];
flag = 1;
}
}
else if(flag == 1)
{
if(array[i] > max)
max = array[i];
else if(array[i] <= max)
{
temp[ind] = i;
ind++;
min = array[i];
flag = 0;
}
}
}
if(max == array[length - 1])
temp[ind] = length;
len = ind;
if(len == 0)
printf("-");
else
{
ind = 0;
while(ind < len)
{
printf("%d ", temp[ind]);
ind++;
}
printf("%d", temp[ind]);
}
free(temp);
}
int splitAndConvert(char* strings, int array[])
{
char* tokenPtr = strtok(strings, " ");

int i = 0;
while(tokenPtr != NULL)
{
array[i] = atoi(tokenPtr);
i++;
tokenPtr = strtok(NULL, " ");
}
return i;
}
int main()
{
char line[1000] = {0};
while(gets(line))
{
int array[100] = {0};
int length = splitAndConvert(line, array);
if(length == 0)
{
break;
}
calculateAndPrint(array, length);
printf("\n");
}
system("pause");
return 0;
}
简单测试用例通过,未提交测试。

1 3 5 7

To make the maximum profit, you should buy at $1 and sell at $5, and then buy at $5 and sell it at $10. so the output is "1 3 5 7".

Input 2

1 1 1 3 5 4 2 2 2 8 10

Ouput 2

3 5 9 11
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: