Keep and Share logo     Log In  |  Mobile View  |  Help  
 
Visiting
 
Select a Color
   
 












01.DS.02.07. Stock Buy Sell to Maximize Profit.html -- 1.6 meg
 Stock Buy Sell to Maximize Profit - Coderust: Hacking the Coding Interview
Log InJoin for free
Back To Module Home
Data Structures
0% completed
Further Reading
Mark Module as Completed
Ask a Question

Stock Buy Sell to Maximize Profit

Given a list of stock prices, find the maximum profit with a single buy or sell activity.

Statement#

We’re given an array of daily stock prices (integers for simplicity). Return the buying and selling prices for making the maximum profit.

The values in the array represent the cost of stock each day. As we can buy and sell the stock only once, we need to find the best buy and sell prices that maximize profit (or minimized loss) over a given span of time.

We need to maximize the profit from a single buy and sell. If we can’t make any profit, we’ll try to minimize the loss.

Example#

For the below examples, the buying and selling prices for making a maximum profit are highlighted:

garray715364array2211211963

Sample input#

[7, 1, 5, 3, 6, 4]

Expected output#

(2, 5)

The image below explains the example shown above.

Try it yourself#

C++
Java
Python
JS
Ruby
Go
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
#include <tuple>
#include <climits>
using namespace std;
tuple<int, int> FindBuySellStockPrices(vector<int>& stockNums) {
    // TODO: Write - Your - Code
    tuple<int, int> t(std::make_pair(-1, -1));
    return t;
}
#
#include <iostream> #include <vector> #include <tuple> #include <climits> using namespace std; tuple<int, int> FindBuySellStockPrices(vector<int>& stockNums) { // TODO: Write - Your - Code tuple<int, int> t(std::make_pair(-1, -1));
Enter to Rename, Shift+Enter to Preview
Test
Need Hint?
Save
Reset

Solution#

With runtime complexity of O(n2)O(n^2)O(n2), a naive solution is to find the maximum gain between each element and its succeeding elements.

There is a tricky linear solution to this problem that requires that we maintaincurrent_buy_price (which is the smallest number seen so far), current_profit, and global_profit as we iterate through the entire array of stock prices. At each iteration, we compare the current_profit with the global_profit, and update the global_profit accordingly.

The basic algorithm is as follows:

current profit = INT_MIN
current buy = stock_prices[0]
global sell = stock_prices[1]
global profit = global sell - current buy

for i = 1 to stock_prices.length:
  current profit = stock_prices[i] - current buy
  if current profit is greater than global profit 
    then update global profit to current profit and update global sell to stock_prices[i]
  if stock_prices[i] is less than current buy 
    then update current buy to stock_prices[i]

return global profit and global sell

Let’s run through a visual representation of the pseudocode:

Created with Fabric.js 3.6.6125919Initial state'current_buy' is set to first element of the array.
1 of 4
C++
Java
Python
JS
Ruby
Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <tuple>
#include <climits>
#include <string>
using namespace std;
tuple<int, int> FindBuySellStockPrices(vector<int>& stockNums) {
    // Return NULL when stock list has a size less than 2
    if (stockNums.size() < 2) {
        tuple<int, int> t(std::make_pair(NULL, NULL));
        return t;
    }
    // Initializations
    int currentBuy = stockNums[0];
    int globalSell = stockNums[1];
    // Calculating the global profit
    int globalProfit = globalSell - currentBuy;
    // Initializing currentProfit with minimum value
    int currentProfit = INT_MIN;
    // Looping over stocks to find best buy and selling price
    for (int i = 1; i < stockNums.size(); i++) {
        // Calculating the current profit
        currentProfit = stockNums[i] - currentBuy;
        // Current profit is greater than the global profit
#
#include <iostream> #include <vector> #include <tuple> #include <climits> #include <string> using namespace std; tuple<int, int> FindBuySellStockPrices(vector<int>& stockNums) { // Return NULL when stock list has a size less than 2
Enter to Rename, Shift+Enter to Preview
Run
Save
Reset

Time complexity#

The time complexity of this solution is O(n)O(n)O(n).

Space complexity#

The space complexity of this algorithm is O(1)O(1)O(1).

Back
Move All Zeros to the Beginning of the Array
Next
Merge an Array With Overlapping Intervals
Mark as Completed
Report an Issue


Creation date: Oct 7, 2022 7:33pm     Last modified date: Oct 7, 2022 7:33pm   Last visit date: Nov 16, 2024 6:36am
    Report Objectionable Content