Prepin
Log in

D

You possess the stock price information for the upcoming n days. Since you are allowed to buy or sell a maximum of one share each day, your goal is to maximize your profit at the end of n days.

Approach / Explanation

The task requires you to determine the highest profit you can make from buying and selling stocks, with the limitation that you can only buy or sell one share each day. Here are the important aspects to keep in mind: You are not required to buy the stock before selling it, so the traditional 'buy low, sell high' approach does not apply here. The restriction is that you can only take one action (either buy or sell) per day, and only for a single share. You will need a list of stock prices for a specified number of days. Your goal is to ascertain the maximum profit achievable through buying and selling the stocks. Solving this problem typically entails identifying local minima and maxima within the provided list of numbers.

Suggested Answer

To calculate the overall profit from daily stock prices, you sum all the positive changes between consecutive days. This approach focuses on making consistent small profits rather than attempting to buy at the lowest price and sell at the highest. By doing so, you can maximize your total profit over time. Below is the corresponding Python code: def maxProfit ( prices ) : max_profit = 0 for i in range ( 1 , len ( prices ) ) : if prices [ i ] > prices [ i - 1 ] : max_profit += prices [ i ] - prices [ i - 1 ] return max_profit For example, with prices set as prices = [7,1,5,3,6,4], calling maxProfit(prices) will yield a return value of 7. The stock price movement follows the pattern 7->1->5->3->6->4, resulting in the profit calculations as follows: (1-7) + (5-1) + (3-5) + (6-3) + (4-6) = 7.

Alternative Answer

Here’s a method that applies the same logic but is written in C++: int maxProfit ( vector < int > & prices ) { int max_profit = 0 ; for ( int i = 1 ; i < prices . size ( ) ; i ++ ) { if ( prices [ i ] > prices [ i - 1 ] ) { max_profit += prices [ i ] - prices [ i - 1 ] ; } } return max_profit ; } In this case: If we have prices = [1,2,3,4,5], calling the function maxProfit(prices) will yield a result of 4. This is because the stock price progresses as 1->2->3->4->5, leading to the profit differences between consecutive days being: (2-1) + (3-2) + (4-3) + (5-4) = 4.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Apple
Dropbox

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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