Hone logo
Hone
Problems

Best Time to Buy and Sell Stock

This challenge asks you to determine the maximum profit that can be obtained from buying and selling a stock once. Understanding how to optimize trading strategies is a fundamental concept in finance and algorithmic trading, and this problem provides a simplified introduction to that area.

Problem Description

You are given an array of integers prices where prices[i] is the price of a given stock on the i-th day. You are allowed to complete at most one transaction (i.e., buy one and sell one share of the stock). Your task is to find the maximum profit you can achieve.

What needs to be achieved: Calculate the maximum profit possible by buying on one day and selling on a later day.

Key requirements:

  • You must buy before you sell.
  • You can only perform one transaction.
  • If you cannot achieve any profit, return 0.

Expected behavior: The function should return an integer representing the maximum profit.

Edge cases to consider:

  • Empty input array.
  • Array with only one element.
  • Prices are always decreasing (no profit possible).
  • Prices are always increasing (maximum profit is the difference between the last and first element).

Examples

Example 1:

Input: [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.  Note that buying on day 2 and selling on day 3 will result in a profit of 3, which is less than 5.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: No transaction results in a profit.

Example 3:

Input: [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
  • Performance: The solution should ideally run in O(n) time complexity.

Notes

Consider using a single pass through the array to keep track of the minimum price seen so far and the maximum profit that can be achieved up to that point. Think about how you can update these values efficiently as you iterate through the prices array. Don't try to find all possible buy/sell combinations; a more efficient approach exists.

Loading editor...
plaintext