用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。 如果只允许进行一次交易,也就是说只允许买一支股票并卖掉,求最大的收益。

用一个数组表示股票每天的价格,数组的第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;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那不勒斯的萤火丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值