Java : O(n) solution using constant space

amazon
Tags: #<Tag:0x00007f1814bcd288>

#1
public int maxProfit(final int[] A) {
    if (A.length <= 1) {
        return 0;
    }
    int prof = 0;
    int min = A[0];

    for (int i = 1; i < A.length; i++) {
        if (A[i] > min && A[i]-min > prof) {
            prof = A[i]-min;
            System.out.println("new prof " + prof);
        }
        else if (A[i] < min) {
            min = A[i];
            System.out.println("new min " + min);
        }
    }
    return prof;
}