美文网首页
Stock Maximize

Stock Maximize

作者: Jeanz | 来源:发表于2017-11-07 11:50 被阅读0次

    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的范围找到当前最大的max,和其index, 那么在[minIndex, index]范围内(都小于max),于是都购买,在index天再卖出去。然后在重复[index+1, n]重复上述步骤。

    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();
        }
    }
    
    
    

    相关文章

      网友评论

          本文标题:Stock Maximize

          本文链接:https://www.haomeiwen.com/subject/dvndmxtx.html