Stock Maximize Discussions | Algorithms | HackerRank

Sort by

recency

|

366 Discussions

|

  • + 0 comments
    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();
        }
    }
    
  • + 0 comments

    lol I overcomplicated this problem for some reason

  • + 0 comments

    Just go from end to beginning

    long stockmax(vector<int> p) {
        long ans = 0; int max_num = 0;
        for(int i = p.size() - 1; i >= 0; i--) 
        {
            max_num = max(max_num, p[i]);
            ans += max(0, max_num - p[i]);
        }
        return ans;
    }
    
  • + 2 comments

    Not a DP problem. Solution is just to iterate backwards. If our current price is greater than the max price, update the max price. If it is smaller, then there is profit to be made - and that profit is the difference between the current price and max price (as we would offload all shares on the max price day).

    def stockmax(prices):
        profit = 0
        maxPrice = 0
        for price in prices[::-1]:
            if price > maxPrice:
                maxPrice = price
            else:
                profit += maxPrice - price
        return profit
    
  • + 0 comments

    Here is my solution in java, javascript, python, C , C++, Csharp HackerRank Stock Maximize Problem Solution