Maximum profit by buying and selling a share at most twice

Maximum profit by buying and selling a share at most twice

Examples:
Input:   price[] = {12 24 15 75 65 90}
Output:  87
Trader earns 87 as sum of 12 and 75
Buy at price 12, sell at 24, buy at 15 and sell at 90

Input:   price[] = {4 32 15 10 18 25 90}
Output:  100
Trader earns 100 as sum of 28 and 72
Buy at price 4, sell at 32, buy at 8 and sell at 90

#include<stdio.h>

void rev(int a[],int n)
{
int i,j,k,b,c,sum1,sum2,sum,max,min;

for(i=0;i<n-1;i++)
{
b=a[0];
if(a[i]<a[i+1])
{
continue;
}

else
sum1=a[i]-b;
k=i+1;
break;
}

min=a[k];
for(i=k;i<n;i++)
{
min=find_min(min,a[k+1]);
}

max=a[k];
for(i=k;i<n;i++)
{
max=find_max(max,a[i]);
}

sum2=max-min;

sum=sum1+sum2;
printf("%d\n",sum);

}

int find_max(int a,int b)
{

if(a>b)
return a;
else return b;

}

int find_min(int a,int b)
{

if(a<b)
return a;
else return b;

}

main()

{

int a[20],low,high,i,temp,n;

printf("Enter Number of array element:\n");
scanf("%d",&n);

printf("Enter array element:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

rev(a,n);

}


Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics