Coding questions · Squarepoint
Maximize profit from one or many stock trades
This question evaluates algorithmic problem-solving skills, particularly efficient array processing and profit-optimization across single-transaction and multiple-transaction variants, along with time and space complexity analysis.
You are given an integer array prices where prices[i] is the price of a stock on day i (0-indexed).
Answer the following two subproblems:
-
Single transaction
- You may complete at most one transaction: choose one day to buy and a later day to sell (must buy before you sell).
- You are not allowed to short-sell.
- Return the maximum profit you can achieve. If you cannot make any profit, return
0.
-
Multiple transactions
- You may complete as many transactions as you like (i.e., buy and sell multiple times), but you cannot hold more than one share at a time (you must sell the stock before you buy again).
- You are not allowed to short-sell.
- Return the maximum total profit you can achieve.
Assume:
1 <= n <= 10^5, wherenis the length ofprices.0 <= prices[i] <= 10^4.
Design efficient algorithms for both subproblems and analyze their time and space complexity.
Max Profit from One Stock Transaction
Return maximum profit from at most one buy before one sell.
Examples
Example 1
Input: ([7,1,5,3,6,4],)
Output: 5
Explanation: Buy low sell high.
Example 2
Input: ([7,6,4,3,1],)
Output: 0
Explanation: No profit.
Hints
- Choose a representation that makes the requested operation direct.
- Handle empty inputs and boundary cases first.
Max Profit from Many Stock Transactions
Return maximum total profit from any number of non-overlapping buy/sell transactions.
Examples
Example 1
Input: ([7,1,5,3,6,4],)
Output: 7
Explanation: Take every positive rise.
Example 2
Input: ([1,2,3,4,5],)
Output: 4
Explanation: Monotone increasing.
Hints
- Choose a representation that makes the requested operation direct.
- Handle empty inputs and boundary cases first.