(Hacker Rank) Stock Maximize - Solution

Link to the problem: https://www.hackerrank.com/challenges/stockmax

The solution below passes through the array checking if there is any element bigger than the current element in its right. If the answer is positive, we buy the current element. Otherwise, if we have any element, we sell it/them.


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numTests = sc.nextInt();
        for (int i = 0; i < numTests; i++) {
            int numNumbers = sc.nextInt();
            int[] numbers = new int[numNumbers];
            for (int j = 0; j < numNumbers; j++) {
                int n = sc.nextInt();
                numbers[j] = n;
            }
           
            long profit = 0;
            int biggerOnTheRight = 0;
            for (int j = numNumbers-1; j >= 0; j--) {
                if (biggerOnTheRight > numbers[j]) {
                    profit = profit-numbers[j]+biggerOnTheRight;
                }
                biggerOnTheRight = Math.max(biggerOnTheRight, numbers[j]);
            }
           
            System.out.println(profit);
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução