-
Notifications
You must be signed in to change notification settings - Fork 4
/
Stock Maximize
91 lines (69 loc) · 1.9 KB
/
Stock Maximize
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
/**
*
Problem Statement
Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next N days.
Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?
Input
The first line contains the number of test cases T. T test cases follow:
The first line of each test case contains a number N. The next line contains N integers, denoting the predicted price of WOT shares for the next N days.
Output
Output T lines, containing the maximum profit which can be obtained for the corresponding test case.
Constraints
1 <= T <= 10
1 <= N <= 50000
All share prices are between 1 and 100000
Sample Input
3
3
5 3 2
3
1 2 100
4
1 3 1 2
Sample Output
0
197
3
Explanation
For the first case, you cannot obtain any profit because the share price never rises.
For the second case, you can buy one share on the first two days, and sell both of them on the third day.
For the third case, you can buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.
*/
import java.util.Scanner;
public class Solution
{
private Scanner in;
public Solution()
{
in = new Scanner(System.in);
}
public void run()
{
int testCases = in.nextInt();
for(int test=0; test<testCases; test++)
{
int n = in.nextInt();
int[] arr = new int[n];
int[] dp = new int[n];
for(int i=0; i<n; i++)
arr[i] = in.nextInt();
int max = arr[n-1];
for(int i=n-1; i>=0; i--)
{
max = (arr[i]>max)?arr[i]:max;
dp[i] = max;
}
long sum = 0;
for(int i=0; i<n; i++)
{
sum += (dp[i] - arr[i]);
}
System.out.println(sum);
}
}
public static void main(String[] args)
{
Solution solution = new Solution();
solution.run();
}
}