DP hackerrank (stock maximize)

STock Maximize (iterative dP  and  branch & bound approach )



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

long long int sell[1000000],a[1000000];

int main()
{
 int t;
 cin>>t;
 while(t--)
 {
  long long int n,i,j,k,ans=0,m=0;
  cin>>n;

  for(i=0;i<n;i++)
   cin>>a[i];

  for(i=n-1;i>=0;i--)
   {
    if(m<a[i]) m=a[i];
    sell[i]=m;
   }

  for(i=0;i<n;i++)
  {
    if(sell[i]>a[i])
   ans+=sell[i]-a[i];
  }
  cout<<ans<<endl;
 }
return 0;
}



-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Branch And  Bound ----------------------------------------------------------




#include<bits/stdc++.h>

using namespace std;

int cost[60000],n;


int solve(int i,int tshare,int property)
{
  if(i==n)
  {
    if(tshare>=1)
     return (property+tshare*cost[i]);
     else
     return property;
  }

  int a,b,c;

  if(tshare>=1)
  {
  a=solve(i+1,tshare+1,property-cost[i]);     /// when buys

  b=solve(i+1,tshare,property);              /// when neither buys nor sells

  c=solve(i+1,tshare-1,property+cost[i]);   /// when sells

   return max(a,max(b,c));
  }

  if(tshare==0)
  {
     a=solve(i+1,tshare+1,property-cost[i]);  /// when buys

     b=solve(i+1,tshare,property);           /// when neither buys nor sells

     return max(a,b);
  }
}





int main()
{
 int t;
 cin>>t;
 while(t--)
 {

   cin>>n;

   for(int i=1;i<=n;i++)
   cin>>cost[i];
   cout<<solve(1,0,0)<<endl;;

 }
return 0;
}

Comments

Popular posts from this blog

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )