0% found this document useful (0 votes)
6 views1 page

Maximize Stock Profit Calculation

The document describes a problem of maximizing profit from stock trading by selecting a day to buy and a future day to sell. It provides a sample test case with input prices and the corresponding output profit. The solution approach involves tracking the minimum price and calculating potential profits, with a time complexity of O(n) and space complexity of O(1).

Uploaded by

yash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Maximize Stock Profit Calculation

The document describes a problem of maximizing profit from stock trading by selecting a day to buy and a future day to sell. It provides a sample test case with input prices and the corresponding output profit. The solution approach involves tracking the minimum price and calculating potential profits, with a time complexity of O(n) and space complexity of O(1).

Uploaded by

yash
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Best Time to Buy and Sell Stock

Description
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to
maximize your profit by choosing a single day to buy one stock and choosing a different day in the
future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot
achieve any profit, return 0.

Sample Test Case


Input: prices = [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.

Solution Approach
We track the minimum price encountered so far and calculate potential profit at each day. The
maximum profit is updated accordingly.

Solution Code
class Solution:
def maxProfit(self, prices):
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit

Time Complexity
Time Complexity: O(n), Space Complexity: O(1)

You might also like