Problem: Link

#include <stdio.h>

/*

* buy day j and sell day i where max(a[i] - a[j]) and i > j

* */

typedef struct

{

int buy, sell, profit;

}Return;

Return maxprofit(int a[], int n)

{

Return r = {n-1, n-1, 0};

Return tmp = r;

n--;

while(n--)

{

if(a[n] < a[tmp.buy])

tmp.buy = n;

if(a[n] > a[tmp.sell])

tmp.buy = tmp.sell = n;

if(tmp.buy < tmp.sell)

{

tmp.profit = a[tmp.sell] - a[tmp.buy];

if(r.profit < tmp.profit)

r = tmp;

}

}

return r;

}

int main()

{

int n;

scanf("%d", &n);

int i;

int a[n];

for(i = 0; i < n; ++i)

scanf("%d", a + i);

Return r = maxprofit(a, n);

printf("buy on: %d and sell on: %d and profit: %d\n", r.buy, r.sell, r.profit);

}

### Like this:

Like Loading...

*Related*

I think you need to changeif(a[n] > a[tmp.sell]) tmp.sell = n;toif(a[n] > a[tmp.sell]) { tmp.sell = n; tmp.buy = n;}or else it won't work for an array like 1, 2, 0