Codility MaxProfit Stock
by ne on 2022-02-16 under Algo/DS/Problems tagged with codility
/**
* Calculate max profit that can be achieved by ONE trade execution / transaction, from a given list of stock prices
*/
public class MaxProfitStock {
public int solution(int[] A) {
if (A.length == 0) return 0;
int b = A[0];
int s = A[0];
int prof = s - b;
int maxProf = prof;
for (int i = 1; i < A.length; i++) {
if (A[i] < b) {
b = A[i];
s = -1;
maxProf = prof;
} else if (A[i] > s) {
s = A[i];
prof = s - b;
if (prof > maxProf)
maxProf = prof;
}
// System.out.println("buy "+b+", sell "+s+" , "+prof+" , maxProf:"+maxProf);
}
return maxProf > 0 ? maxProf : 0;
}
public static void main(String... args) {
System.out.println(new MaxProfitStock().solution(new int[]{23171, 21011, 21123, 21366, 21013, 21367}));
}
}