Stock Buy Sell to Maximize Profit

Difficulty Level Easy
Frequently asked in Amazon Apple Facebook Microsoft Morgan Stanley PayPal Qualtrics TCS Uber
Array GreedyViews 4599

Problem Statement

In the “Stock Buy Sell to Maximize Profit” problem we have given an array that contains stock price on each day, find the maximum profit that you can make by buying and selling in those days. Here, we can buy and sell multiple times but only after selling a stock, you can buy another stock.

Input Format

The first line containing an integer n.

Second-line containing n space-separated integers.

Output Format

Print an integer that denotes the maximum profit we can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Example

6
7 1 5 3 6 4
7

Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Algorithm for Stock Buy Sell to Maximize Profit

In this case, instead of looking for every peak following a valley, we can simply go on crawling over the slope and keep on adding the profit obtained from every consecutive transaction. In the end,we will be using the peaks and valleys effectively, but we need not track the costs corresponding to the peaks and valleys along with the maximum profit, but we can directly keep on adding the difference between the consecutive numbers of the array if the second number is larger than the first one, and at the total sum we obtain will be the maximum profit. This approach will simplify the solution.

This can be made clearer by taking this example: [1, 7, 2, 3, 6, 7, 6, 7]

Stock Buy Sell to Maximize Profit

From the above graph, we can observe that the sum  is equal to the difference  corresponding to the difference between the heights of the consecutive peak and valley.

Implementation

C++ Program for Stock Buy Sell to Maximize Profit

#include <bits/stdc++.h>
using namespace std;

int maxProfit(int prices[], int n) 
{
    int maxprofit = 0;
    for(int i=1;i<n;i++) 
    {
        if(prices[i]>prices[i-1])
            maxprofit+=prices[i]-prices[i-1];
    }
    return maxprofit;
}
    
int main()
{
   int n;
   cin>>n;
   int a[n];
   for(int i=0;i<n;i++)
   {
       cin>>a[i];
   }
   cout<<maxProfit(a,n);
   return 0;
}

Java Program for Stock Buy Sell to Maximize Profit

import java.util.ArrayList;
import java.util.Scanner;
class sum
{
    public static int combination(int arr[], int n) 
    { 
        int maxprofit = 0;
        for (int i = 1; i < n; i++) {
            if (arr[i] > arr[i - 1])
                maxprofit += arr[i] - arr[i - 1];
        }
        return maxprofit;
    } 
    public static void main(String[] args)
    {
        Scanner sr = new Scanner(System.in);
        int n = sr.nextInt();
        int a[] = new int [n];
        for(int i=0;i<n;i++)
        {
            a[i] = sr.nextInt();
        }
        int ans = combination(a, n);
        System.out.println(ans);
    }
}
7
65 32 531 1 65 43 876
1396

Complexity Analysis for Stock Buy Sell to Maximize Profit

Time Complexity

O(n) where n is the size of the given array. Here we traverse the whole array just one-time ans update our answer.

Space Complexity

O(1) because we don’t use any auxiliary space here.

Translate »