
Patrick B. answered 06/04/21
Math and computer tutor/teacher
/*******************************
SORRY
*************************/
using namespace std;
#include <iostream>
#include <stdlib.h>
typedef struct _TPriceRec
{
int buyDayNum;
int sellDayNum;
int netResult;
} * TPriceRec;
#define PRICE_REC_SIZE (sizeof(struct _TPriceRec))
int ComparePriceRec( const void * rec1, const void * rec2)
{
TPriceRec priceRec1 = (TPriceRec)rec1;
TPriceRec priceRec2 = (TPriceRec)rec2;
return (priceRec1->netResult - priceRec2->netResult);
}
Go()
{
int N=15;
int prices[] ={ 200, 500, 800, 100, 300, 50, 300, 450, 720, 90, 30, 50, 900, 500, 70};
int n = N*(N+1)/2;
TPriceRec priceRecs = (TPriceRec) malloc(sizeof(struct _TPriceRec)*n);
int iIndexPos=0;
for (int iLoop=0; iLoop<N; iLoop++)
{
for (int jLoop=iLoop+1; jLoop<N; jLoop++)
{
struct _TPriceRec curPriceRec;
curPriceRec.buyDayNum=iLoop;
curPriceRec.sellDayNum = jLoop;
curPriceRec.netResult = prices[jLoop]-prices[iLoop];
priceRecs[iIndexPos++] = curPriceRec;
}
}
qsort(priceRecs,n,PRICE_REC_SIZE,ComparePriceRec);
//Buy on day #10, sell on day #12, max profit = 870
cout << " Buy on day # " << priceRecs[n-1].buyDayNum << endl;
cout << " Sell on day # " << priceRecs[n-1].sellDayNum << endl;
cout << " max profit = " << priceRecs[n-1].netResult << endl;
}