This is not the max-profit algorithm, but a variation of it.
I have an array A, where A[i] corresponds to the price of computers in country A and time i. And B[i] corresponds to the price of computers in country B and time i.
All entries in each array are positive integers. I want to buy computers in country A at some time i and then sell them in country B at some later time j > i.
I need to maximize profit B[j] − A[i].
Example:
A = [40, 18, 20, 25, 12, 13, 19, 20, 5, 7, 3]
B = [15, 50, 5, 30, 34, 19, 28, 33, 20, 20, 20]
The maximum possible profit is B[7] − A[4] = 33 − 12 = 21, so the output should be 21.
I want this to run in O(n).
This is what I have so far.
static int maxProfit(int pricesA[], int pricesB[]) {
int maxProfit = 0;
for (int i = 0; i < pricesA.length; i++) {
for (int j = 1; j < pricesB.length; j++) {
if (pricesB[j - 1] > pricesA[i]) {
maxProfit = pricesB[j - 1] - pricesA[i];
}
}
}
return maxProfit;
}
However, I'm having trouble with getting the selling the computer at a time j > i part. Right now, I'm comparing every time in B[j] with A[i] when it should be that I buy at time A[i] and sell it for a profit at time B[j] where index j is greater than index i.