-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStock_Buy_Sell.java
96 lines (78 loc) · 1.71 KB
/
Stock_Buy_Sell.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Infinte Transactions allowed .
// Given array where each element denotes the price of stock at particular day . We need to maximize the profit
import java.io.*;
import java.util.*;
import java.lang.Math;
class Interval
{
int buy;
int sell;
}
public class GFG
{
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int T =s.nextInt();
while(T-->0)
{
int n = s.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++)
{
arr[i] = s.nextInt();
}
if(n == 2)
{
int td = arr[1]-arr[0];
if(td>0)
{
System.out.println("(0 1)");
}
else
{
System.out.println("No Profit");
}
}
else
{
Stock(arr,n);
}
}
}
public static void Stock(int arr[] , int n)
{
ArrayList<Interval> al = new ArrayList<>();
int i = 0;
int count = 0;
while(i<n-1)
{
// Find local minima so that we purchase on that day
while((i<n-1) && arr[i]>=arr[i+1])
i++;
if(i == n-1)
break;
Interval e = new Interval();
e.buy = i;
i++;
// Find local maxima so that we sell on that day
while((i<n-1) && arr[i]<=arr[i+1])
i++;
e.sell = i;
// add to arraylist
al.add(e);
count++;
}
if(count == 0)
{
System.out.println("No Profit");
}
else
{
for(int k=0;k<count;k++)
{
System.out.print("("+al.get(k).buy+" "+al.get(k).sell+")"+" ");
}
System.out.println();
}
}
}