To find best days for sell and buy, if array of stock prices given


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);
}
Advertisements

One thought on “To find best days for sell and buy, if array of stock prices given

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s