https://www.hackerrank.com/challenges/stockmax/problem
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:
Sample Input
3(test case)
3(days)
5 3 2(price in each day)
3
1 2 100
4
1 3 1 2
Sample Output
0
197
3
題解:首先在minIndex和n的范圍找到當(dāng)前最大的max,和其index, 那么在[minIndex, index]范圍內(nèi)(都小于max),于是都購(gòu)買,在index天再賣出去。然后在重復(fù)[index+1, n]重復(fù)上述步驟。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static long maxProfit(int[] price){
int n = price.length;
long profit = 0L;
int minIndex = 0;
while (minIndex < n) {
int max = 0;
int index = -1;
for (int p = minIndex; p < n; p++) {
if (price[p] >= max) {
max = price[p];
index = p;
}
}
int maxIndex = index + 1;
while (index >= minIndex) {
profit += max - price[index];
index--;
}
minIndex = maxIndex;
}
return profit;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
int[] arr = new int[n];
for(int arr_i = 0; arr_i < n; arr_i++){
arr[arr_i] = in.nextInt();
}
System.out.println(maxProfit(arr));
}
in.close();
}
}