Stocks are Profitable Problem Statement

You are provided with an array/list 'prices', where each element signifies the prices of a stock as of yesterday and the indices represent minutes. The task is to determine and return the maximum profit possible from a single buy and sell action of the stock. Note that you can buy and sell the stock only once.

Input:

The first line indicates a single integer 'T', representing the number of test cases. Each test case starts with an integer 'N', denoting the size of the array, followed by a line of 'N' space-separated integers that represent the elements of the 'prices' array.

Output:

For each test case, output a single integer which denotes the maximum achievable profit. If the maximum profit turns negative, output '0'. Each test case's output should be printed on a new line.

Example:

Input:
prices = [2, 100, 150, 120]
Output:
148
Explanation:

The stock can be bought at minute 0 when the price is Rs. 2 and sold at minute 2 when the price is Rs. 150, resulting in a maximum profit of 148.

Constraints:

  • 1 <= T <= 10
  • 2 <= N <= 104
  • 1 <= ARR[i] <= 109
  • Time Limit: 1 sec

Note:

You can't sell the stock before buying it.
AnswerBot
3d

Given stock prices, find the maximum profit from a single buy and sell action.

  • Iterate through the array and keep track of the minimum price seen so far and the maximum profit achievable.

  • Calculate the ...read more

120 Thanuja
1y
int bestTimeToBuyAndSellStock(vector<int>&prices) { int maxi=0; int mini=INT_MAX; int n=prices.size(); for(int i=0;i<n;i++){ mini=min(mini,prices[i]); maxi=max(maxi,prices[i]-mini); } return maxi; } 
Help your peers!
Add answer anonymously...
Trilogy Innovations Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter