Algorithms‎ > ‎

Maximum Profit or Loss in Stock Trading (Java)

static double calculateMaxProfit(double values[])

{

double max = Double.MIN_VALUE, maxDiff = Double.MIN_VALUE, diff = 0;

double bottom = values[0];

for(int i = 1; i < values.length ; i++)

{

diff += values[i] - values[i - 1];

if (diff > maxDiff)

{

maxDiff = diff;

max = values[i];

}

if (values[i] < bottom)

{

bottom = values[i];

diff = 0;

}

}

System.out.println("Maximum Profit: " + maxDiff + " Buy: " + (max - maxDiff) + " Sell: " + max);

return maxDiff;

}

static double calculateMaxLoss(double values[])

{

double min = Double.MAX_VALUE, maxLoss = Double.MAX_VALUE, diff = 0;

double peak = values[0];

for(int i = 1; i < values.length ; i++)

{

diff += values[i] - values[i - 1];

if (diff < maxLoss)

{

maxLoss = diff;

min = values[i];

}

if (values[i] > peak)

{

peak = values[i];

diff = 0;

}

}

System.out.println("Maximum Loss: " + maxLoss + " Buy: " + (min - maxLoss) + " Sell: " + min);

return maxLoss;

}