Given an array prices[] of non-negative integers representing a stock price on…

PYQ Accenture Hiring Assessment 2024

Given an array prices[] of non-negative integers representing a stock price on each day, find the maximum profit obtainable with at most one transaction. One transaction consists of one buy followed by one sell on a later day. Return 0 when no positive profit is possible.

Note: The stock must be bought before it is sold.

Input format

  • The first line contains a single integer n — the number of days, that is the size of prices[].

  • The second line contains n space-separated integers prices[0], prices[1], …, prices[n-1].

Output format

Print a single integer — the maximum profit obtainable with at most one transaction, or 0 when no positive profit is possible.

For prices[] = [1, 3, 6, 9, 11] the standard input is:

5
1 3 6 9 11

and the required standard output is:

10

Examples

  • Input: prices[] = [7, 10, 1, 3, 6, 9, 2]

    Output: 8

    Explanation: Buy at index 2 for price 1 and sell at index 5 for price 9. The profit is 9 - 1 = 8.

  • Input: prices[] = [7, 6, 4, 3, 1]

    Output: 0

    Explanation: Prices decrease throughout, so no later selling price exceeds an earlier buying price.

  • Input: prices[] = [1, 3, 6, 9, 11]

    Output: 10

    Explanation: Buy at index 0 for price 1 and sell at the last index for price 11. The profit is 10.

Constraints

  • 1 ≤ prices.size() ≤ 105

  • 0 ≤ prices[i] ≤ 104

Attempted by 3 students.

Sign up free to check your answer

Sign up free

Explore the full course: Accenture Preparation

Loading lesson…