Stock Maximize

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


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容