#K51747. Maximize Stock Profit

    ID: 29156 Type: Default 1000ms 256MiB

Maximize Stock Profit

Maximize Stock Profit

You are given an array of stock prices for consecutive days. Your task is to determine the maximum profit that can be achieved by engaging in as many transactions as you like, with the constraint that you must sell the stock before buying it again. In each transaction, you can only buy once and sell once, and you can perform multiple transactions sequentially.

The strategy is simple: add the profit for every pair of consecutive days where the price increases. Mathematically, if the stock prices on days \(1, 2, \dots, n\) are given by \(a_1, a_2, \dots, a_n\), then the maximum profit is computed as:

\[ \text{Profit} = \sum_{i=2}^{n} \max(0, a_i - a_{i-1}) \]

This ensures that you accumulate profit for every increase between consecutive days, while ignoring days where the price does not increase.

inputFormat

The input is read from standard input (stdin) and is formatted as follows:

The first line contains an integer (n) ((1 \leq n \leq 10^5)), representing the number of days. The second line contains (n) space-separated integers, where each integer represents the stock price on that day.

outputFormat

Output a single integer to standard output (stdout) representing the maximum profit that can be achieved by performing the allowed transactions.## sample

6
7 1 5 3 6 4
7