Monday, 29 February 2016

Problem Statement - I

Problem Statement:
              You have been given a gold prices for n days. You Need to find out max benefit in best time to buy and sell.

import java.util.*;
class Demo
{
  public static void main(String s[])
  {
  Scanner sc = new Scanner(System.in);
       int day[]=new int[100];
        int i,j,res,a=0,b=0,fres=0;
       System.out.println("\nEnter no of days: ");
  int n=sc.nextInt();

  System.out.print("\nEnter "+n+" gold prices: ");
  for(i=0;i<n;i++)
  {
    day[i]=sc.nextInt();
  }
  for(i=0;i<n;i++)
  {
    for(j=i;j<n;j++)
    {
    res=day[j]-day[i];
    System.out.print("Purchase Day: "+(i+1)+" Sell Day: "+(j+1)+" Profit: "+res);
    if(res>=fres)
    {
      a=i;
      b=j;
      fres=res;
    }
    System.out.println();
    }
  }

    System.out.print("\nBest Purchase:\nPurchase Day: "+(a+1)+" Sell Day: "+(b+1)+" Profit: "+fres);
  }
}

Output:
Enter no of days:
5

Enter 5 gold prices: 
100
60
400
500
30

Purchase Day: 1 Sell Day: 1 Profit: 0
Purchase Day: 1 Sell Day: 2 Profit: -40
Purchase Day: 1 Sell Day: 3 Profit: 300
Purchase Day: 1 Sell Day: 4 Profit: 400
Purchase Day: 1 Sell Day: 5 Profit: -70
Purchase Day: 2 Sell Day: 2 Profit: 0
Purchase Day: 2 Sell Day: 3 Profit: 340
Purchase Day: 2 Sell Day: 4 Profit: 440
Purchase Day: 2 Sell Day: 5 Profit: -30
Purchase Day: 3 Sell Day: 3 Profit: 0
Purchase Day: 3 Sell Day: 4 Profit: 100
Purchase Day: 3 Sell Day: 5 Profit: -370
Purchase Day: 4 Sell Day: 4 Profit: 0
Purchase Day: 4 Sell Day: 5 Profit: -470
Purchase Day: 5 Sell Day: 5 Profit: 0

Best Purchase:
Purchase Day: 2 Sell Day: 4 Profit: 440