Stock minimisation question

Apr 24, 2016 at 3:15pm
Hi, in this programming assignment I am required to find out the maximum profit (positive or negative) that can be earned during the week, given by a buyer. A person can buy share on any day and sell on any day, provided that day of selling > day of buying. Up to the point my code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

int big_number = 1e99;
int bottom = big_number;
int top = 0;
int profit = 0;
int potential_profit;

int prices[] = {44000, 54000, 46000, 47000, 48000}; // array of prices
int numPrices = 5; // number of prices

int main()
{
for (int i=0; i<numPrices; i++)
{
    if (prices[i] < bottom) // determines the lowest buy value
    {
        bottom = prices[i];
    }
    else if (prices[i] > top) // determines the highest sell value
    {
        top = prices[i];
    }
    {
        potential_profit = top - bottom;
    }
}
    profit = potential_profit;
    cout << "Best buy: " << bottom << endl;
    cout << "Best sell: " << top << endl;
    cout << "Profit: " << profit << endl;
}


The question I have is how to make sure that a buyer buys a share firsthand and sells it only after having obtained it, for the array 'prices[]': 67000, 73000, 57000, 63000, 47000. In other words how to make sure that the share firstly is bought and sold only after obtained? Thank you.

P.S.I know that it has to do with O(n^2), but I have no idea what that means. Thank you very much for the help!
Last edited on Apr 24, 2016 at 3:17pm
Apr 24, 2016 at 3:21pm
This is the Codility "Max Profit" task. There are many solutions available on the web.

https://www.google.co.uk/#q=codility+max+profit

The key is to start at the beginning of the array, and work forwards, keeping track of the highest profit you could have made so far.

It's not O(n^2), it's O(n)
Apr 24, 2016 at 3:51pm
int big_number = 1e99;
We have something for that already that's a lot more reliable; http://en.cppreference.com/w/cpp/types/numeric_limits/max
int big_number = std::numeric_limits<int>::max();
Topic archived. No new replies allowed.