Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Buy Sell Stock and Pair Target
00:00
5 left

Buy Sell Stock and Pair Target

HardPython

Problem

Motorola MOTOTRBO analytics receives a sequence of daily price values. Given prices and a target, find both the most profitable single buy and sell transaction and a pair of distinct entries whose values sum to target.

You must buy before selling. Return a dictionary with three fields: profit, the maximum possible profit; trade, the [buy_index, sell_index] producing that profit; and pair, two indices whose values sum to target. If no profitable trade exists, return trade as [-1, -1] and profit as 0. If no valid pair exists, return pair as [-1, -1].

For ties, choose the lexicographically smallest index pair. A pair may not reuse the same array element. The input array is not sorted and must not be modified.

Formal Specification

  • Input: an integer array prices and an integer target.
  • Output: a dictionary with keys profit, trade, and pair.
  • trade and pair contain zero-based indices.

Constraints

  • 2 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^9
  • -10^9 <= target <= 2 * 10^9
  • The input array must not be modified
  • A pair cannot reuse the same index

Function Signature

def best_trade_and_pair(prices, target):
Interviewer

Your question is Buy Sell Stock and Pair Target. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.