no offense but needs work
1 2 3 4 5 6 7 8
|
Enter wheat prices per bushel of six consecutive days: 10
1
2
3
4
4
max profit was: (max-min) 0 as max=10 and previous min=10
|
also I think you can't take absolutes. it ordered, so 10 followed by 1 .. you can't time travel, can you?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
using namespace std;
int main()
{
int input[] = { 5,5,4,6,5,5};
int j = 0;
int k = 5;
int mx = input[5];
int mn = input[0];
do
{
if( input[k] >= mx)
mx = input[k--];
else
if(input[j] <= mn)
mn=input[j++];
else {j++; k--;}
} while( j<=k);
cout<< mx << " " << mn << endl;
}
|
ok maybe it works now. seems to for a few test cases. current test case does not work, but the code is close and gives you an idea of what the answer might look like.
which does not answer the problem.. how do you approach it?
being pretty solid with the language I coded first and messed with it to debug it, which is terrible for a serious problem. What you should do is solve it on paper for several conditions... what if day 1 most expensive and day 2 is cheapest, what is the answer? Your default test, of course. And so on. After doing that, ask what you need... you need an array of values, a way to iterate it, and a way to track your best answer so far, and an algorithm to improve your answer as you iterate the array. All but the algorithm translate into variables which you see in the code. The algorithm.. well, I decided (hopefully its correct) that I needed to start on the ends of the array and work towards the middle until the tracking variables crossed each other, looking at each step for an improvement, and if no improvement is found, move on toward the center.