/* 
 * Solution to Problem 4 (C++)
 * 11th Annual CS Programming Contest
 * WCU Dept of Math and CS
 * Copyright 2000, All Rights Reserved
 *
 * Problem Description: Stock Market Problem from page 190- 196 of
 * Kamin98. Read in the values of a stock for a sequence of
 * consecutive days and find the best pair of days to have bought and
 * sold the stock to maximize your profit. There is only one buy day
 * and one sell day.
 */

#include <iostream.h>

int main() {

  /* I initialize the big_diff to 0 because the profit for buying and
   * selling on the first day is 0.
   * 
   * The buy- sell- and low- days are initialized to 1 because that is
   * what they should be on the first day.
   */

  // biggest profit possible so far: starts at 0.
  int big_diff = 0;
  // sell price so far
  int sell_at;
  // sell day so far: starts at 1.
  int sell_day = 1;
  // maximum profit for the current day: starts at 0.
  int current_diff = 0;
  // lowest price so far
  int low;
  // lowest price day so far: starts at 1.
  int low_day = 1;
  // buy price so far
  int buy_at;
  // buy day so far: starts at 1.
  int buy_day = 1;
  int input, day = 1;

  // The first day input is treated specially.
  cout << "Enter the value of the stock on day 1: ";
  cin >> input;

  // On the first day, input is the lowest AND the highest value
  // entered so far:
  low = input;
  buy_at = input;
  sell_at = input;

  if (input != -1) {
    cout << "Enter the value of the stock on day " << ++day << ": ";
    cin >> input;
  }
  while (input != -1) {
    // Update the value of low and low_day.
    if (input < low) {
      low = input;
      low_day = day;
    }

    // Calculate maximum profit for selling today.  The max profit for
    // selling today will be the difference between today's price and
    // the lowest price so far.
    current_diff = input - low;

    // If today's max profit is bigger than the biggest so far,
    if (current_diff > big_diff) {
      // then change the buy and sell data
      big_diff = current_diff;
      sell_at = input;
      sell_day = day;
      buy_at = low;
      buy_day = low_day;
    }

    cout << "Enter the value of the stock on day " << ++day << ": ";
    cin >> input;
  } 

  // Report the results:  
  // If sell_at is -1, that can only mean that no data was entered.
  if (sell_at == -1)
    cout << "No data entered.  Goodbye.\n";
  else
    cout << "Maximum profit comes from buying on day " << buy_day
         << " and selling on day " << sell_day << ".\n"
         << "The maximum profit is $" << big_diff << ".\n"
         << "Goodbye.\n";

  return 0;
}
