Suppose the price of a stock is stored in an array in chronological order. What is the maximum profit that can be made by trading the stock at one time?

Example 1:

Input: [7,1,5,3,6,4] output: 5 explanation: buy on day 2 (stock price = 1) and sell on day 5 (stock price = 6), maximum profit = 6-1 = 5. Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price. Example 2:

Input: [7,6,4,3,1] output: 0 explanation: in this case, no transaction is completed, so the maximum profit is 0.

Limitations:

0 <= Array length <= 10^5

java

【 1,2,3,4,5 】 first calculate the tiring product from each position in the positive order to the left end, and get the original result. Then calculate the tiring product from each position in the reverse order to the right end, and get the final result.

class Solution {
    public int[] constructArr(int[] a) {
        int[] ans = new int[a.length];
        for (int i = 0, p = 1; i < a.length; i++) {
            ans[i] = p;
            p *= a[i];
        }
        for (int i = a.length - 1, p = 1; i >= 0; i--) {
            ans[i] *= p;
            p *= a[i];
        }
        returnans; }}Copy the code