Prepin
Log in

Highest Profit

Approach / Explanation

The "Maximum Profit" question in the Algorithms section typically involves an array of numbers that represent stock prices over various days. The term 'maximum profit' refers to the highest profit achievable by purchasing the stock on one day and selling it on another. Here are some key points to keep in mind when addressing this question: We can only buy and sell the stock one time. The day we sell must be later than the day we buy. If there is no chance for profit, meaning the highest price is lower than the purchase price, we should return 0 to indicate that no transaction should occur.

Suggested Answer

For example, consider the prices = [7, 1, 5, 3, 6, 4]. The optimal profit can be obtained by purchasing on the second day when the price is 1 and selling on the fifth day for 6, resulting in a profit of 5. Here’s a method to tackle this problem: Start by initializing two variables: minPrice = Infinity and maxProfit = 0. Loop through the price array from the beginning to the end. For each price, update minPrice to be the lesser of minPrice and the current_price, and update maxProfit to be the greater of maxProfit and (current_price - minPrice). Finally, return maxProfit. This approach ensures that you buy at the lowest price and sell at the highest price possible after the purchase.

Alternative Answer

In the case of the price set - [7,6,4,3,1] arranged in descending order, you would not generate any profit, as the selling price is consistently lower than the buying price. Therefore, the algorithm should return '0' in this situation. The method outlined previously is also applicable here. The algorithm iterates through each price while simultaneously keeping track of the lowest price and the highest profit. However, since the prices are decreasing, the maximum profit will be 0, as no profitable transactions can occur.

Question Details

Difficulty & Category

Medium
algorithms

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.