股票问题
题目描述:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
题目来源:力扣(LeetCode)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
printf("please input the n\n");
scanf("%d",&n);
int *a=(int *)malloc(sizeof(int)*(n+1));
//在这里用一下这种建立数组的写法
int i;
printf("please input the a[i] from 1 to n \n");
for(i=1;i<=n;i++) //将a[i]存第i天的股票价格
{
scanf("%d",&a[i]);
}
int buy,sale,profit;
int profit_max=0;
int profit_max_total=0;
buy=a[1];
sale=a[1];
for( i=2;i<=n;i++ )
{
if(sale>a[i])
{
profit_max_total+=profit_max;
profit_max=0;
printf("the buy sale profit is:%d--%d--%d\n",buy,sale,profit_max_total);
sale=a[i];
buy=a[i];
}
else if(buy>a[i])
{
buy=a[i];
}
else if(a[i]-buy>profit_max)
{
profit_max=a[i]-buy;
sale=a[i];
}
}
profit_max_total+=profit_max;
printf("the buy sale profit is:%d--%d--%d\n",buy,sale,profit_max_total);
// printf("%d",profit_max_total);
free(a);
}