|
U
Pro43. Best Time to Buy and Sell Stock
Med.
Problem Description
Given an array of N integers representing daily stock prices, find the maximum profit obtainable from completing at most one transaction (one buy and one sell, with sell occurring after buy). If no profit can be made, output 0.
Input Format
- •Line 1: An integer N (1≤N≤105).
- •Line 2: N space-separated integers P1,…,PN.
Output Format
Print the maximum profit.
Example 1:
Input:
6 7 1 5 3 6 4
Output:
5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.
Example 2:
Input:
5 7 6 4 3 1
Output:
0
Explanation: Prices decrease monotonically; maximum profit is 0.
Example 3:
Input:
2 2 4
Output:
2
Explanation: Buy at 2, sell at 4, profit = 2.
Constraints:
Standard integer bounds: 32-bit signed integer or input range [1, 10^5].Time complexity target: O(N) or O(N log N) where applicable.Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit