用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。 如果只允许进行一次交易,也就是说只允许买一支股票并卖掉,求最大的收益。
提示:从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求。 根据买卖股票的特性,我们必须先低价买,再高价卖,这个找最大收益的过程实际上是找到目前为之的最低价。在遍历价格数组时,根据这个动态更新的最低价和当前的价格可以算出当前卖股票最大能赚多少钱。
输入提示信息:"Please input the array size\n"
输入格式:"%d"
数组输入提示信息:"Please input the %d-th number\n"
输入格式:"%d"
输出格式:"the maxProfit is %d\n"
函数原型为
int maxProfit(int prices[], int n)
注:不考虑非法输入
程序运行示例
Please input the array size
4
Please input the 0-th number
1
Please input the 1-th number
2
Please input the 2-th number
3
Please input the 3-th number
4
the maxProfit is 3
#include <stdio.h>
int FindMax(int *a,int n);
int main()
{
int n,a[n],i;
printf("Please input the array size\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Please input the %d-th number\n",i);
scanf("%d",&a[i]);
}
printf("the maxProfit is %d\n",FindMax(a,n));
return 0;
}
int FindMax(int *a,int n)
{
int i,j,t;
t = 0;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]>a[i])
{
t = j;
}
}
}
return t;
}