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
4mo
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


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

