Best Time to Buy and Sell Stock 2#11613

Let's consider how the stock price changes every day. If the price increases from day i - 1 to day , then we include the difference prices_i - prices_{i - 1} in the total profit.

Example

Consider the first example.

The profit will be 3 + 6 = 9.

Algorithm realization

Read the input data.

scanf("%d", &n);
prices.resize(n);
for (i = 0; i < n; i++)
  scanf("%d", &prices[i]);

In the variable , we compute the maximum possible profit.

res = 0;
for (int i = 1; i < prices.size(); i++)

If the stock price increases from day i - 1 to day , then we add the profit prices_i - prices_{i - 1} to the result .

  if (prices[i] > prices[i - 1])
    res += prices[i] - prices[i - 1];

Print the answer.

printf("%d\n", res);

Python realization

Read the input data.

n = int(input())
prices = list(map(int, input().split()))

In the variable , we compute the maximum possible profit.

res = 0
for i in range(1, len(prices)):

If the stock price increases from day i - 1 to day , then we add the profit prices_i - prices_{i - 1} to the result .

  if prices[i] > prices[i - 1]:
    res += prices[i] - prices[i - 1]

Print the answer.

print(res)