Saturday, September 12, 2015

Find the maximum possible profit in an array of share prices

Problem:
Given an array of integers which are share prices, find the maximum possible profit that can be earned by buying and selling the shares on particular dates. Also output the dates (indices) on which the buying and selling should happen in order to earn the maximum profit.


Sample Input:
15
1 3 2 4 5 3 1 0 1 -1 1 2 3 5 4


Sample Output:
Buy date: 9
Sell date: 13
Buying price: -1
Selling price: 5
Maximum possible Profit: 6
 
Approach 1: Time complexity: O(n2), Space complexity: O(1)
Code:
#include <iostream>
using namespace std;

int main() 
{
 int A[100];
 int n;
 cin>>n;
 for(int i=0;i<n;i++)
 {
  cin>>A[i];
 }
 int profit = 0;
 int maxProfit = 0;
 int buyDate = 0;
 int sellDate = 0;
 for(int i=0;i<n;i++)
 {
  for(int j=i+1;j<n;j++)
  {
   profit = A[j] - A[i];
   if(profit > maxProfit)
   {
    buyDate = i;
    sellDate = j;
    maxProfit = profit;
   }
  }
 }
 cout<<"Buy date: "<<buyDate<<endl;
 cout<<"Sell date: "<<sellDate<<endl;
 cout<<"Buying price: "<<A[buyDate]<<endl;
 cout<<"Selling price: "<<A[sellDate]<<endl;
 cout<<"Maximum possible Profit: "<<maxProfit<<endl;
 return 0;
}

Approach 2: Time complexity: O(n), Space complexity: O(1)
Code:
#include <iostream>
using namespace std;

int main() {
 int A[100];
 int n;
 cin>>n;
 for(int i=0;i<n;i++)
 {
  cin>>A[i];
 }
 int currMaxIndex = 0;
 int currMinIndex = 0;
 int sellDate = 0;
 int buyDate = 0;
 int profit = 0;
 int maxProfit = 0;
 int currMinPrice = 0;
 int currMaxPrice = 0;
 if(A[0] < A[1])
 {
  currMaxIndex = 1;
  currMaxPrice = A[1];
  currMinIndex = 0;
  currMinPrice = A[0];
 }
 else
 {
  currMaxIndex = 0;
  currMaxPrice = A[0];
  currMinIndex = 1;
  currMinPrice = A[1];
 }
 for(int i=0;i<n;i++)
 {
  if(A[i] <= currMinPrice)
  {
   currMinIndex = i;
   currMinPrice = A[i];
  }
  if(A[i] >= currMaxPrice)
  {
   currMaxIndex = i;
   currMaxPrice = A[i];
  }
  if(currMaxIndex > currMinIndex)
  {
   profit = A[currMaxIndex] - A[currMinIndex];
   if(profit > maxProfit)
   {
    maxProfit = profit;
    buyDate = currMinIndex;
    sellDate = currMaxIndex;
   }
  }
 }
 cout<<"Buy date: "<<buyDate<<endl;
 cout<<"Sell date: "<<sellDate<<endl;
 cout<<"Buying price: "<<A[buyDate]<<endl;
 cout<<"Selling price: "<<A[sellDate]<<endl;
 cout<<"Maximum possible Profit: "<<maxProfit<<endl;
 return 0;
}

2 comments: