/* Topcoder SRM 699, D2, 250-Pointer: UpDownHiking. * James S. Plank * Wed Nov 23 15:22:45 EST 2016 */ #include #include #include using namespace std; class UpDownHiking { public: int maxHeight(int N, int A, int B); }; int UpDownHiking::maxHeight(int N, int A, int B) { int Day; /* We'll run through each day, from day 1 to day N */ int Up; /* This is our altitude at the beginning of each day, if we only went up. */ int Down; /* This is our altitude if we started at N*B and only went down each day. */ int Min; /* For each day, we record the minimum of Up and Down here. */ int Best; /* This is the maximum value of Min */ Up = 0; Down = N*B; Best = 0; /* This loop is simple enough that it doesn't really need any comments. We're going to maintain the values of Up and Down for each day, from 1 to N, calculate the minimum value, and then keep track of the best of these. */ for (Day = 1; Day <= N; Day++) { printf("Day %d: %4d or %4d\n", Day, Up, Down); Up += A; Down -= B; Min = (Up < Down) ? Up : Down; Best = (Min > Best) ? Min : Best; } return Best; }