HackerRank Stock Maximize Problem Solution Yashwant Parihar, July 2, 2023August 1, 2024 In this post, we will solve HackerRank Stock Maximize Problem Solution. 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 number of 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? Exampleprices = [1,2]Buy one share day one, and sell it day two for a profit of 1. Return 1.prices = [2,1]No profit can be made so you do not buy or sell stock those days. Return 0. Function Description Complete the stockmax function in the editor below. stockmax has the following parameter(s): prices: an array of integers that represent predicted daily stock prices Returns int: the maximum profit achievable Input Format The first line contains the number of test cases t. Each of the next t pairs of lines contain:– The first line contains an integer n, the number of predicted prices for WOT.– The next line contains n space-separated integers prices[i], each a predicted stock price for day . Sample Input STDIN Function ----- -------- 3 q = 3 3 prices[] size n = 3 5 3 2 prices = [5, 3, 2] 3 prices[] size n = 3 1 2 100 prices = [1, 2, 100] 4 prices[] size n = 4 1 3 1 2 prices =[1, 3, 1, 2] Sample Output 0 197 3 ExplanationFor the first case, there is no profit because the share price never rises, return 0. For the second case, buy one share on the first two days and sell both of them on the third day for a profit of 197.For the third case, buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4. The overall profit is 3. HackerRank Stock Maximize Problem Solution Stock Maximize C Solution #include <stdio.h> #include <stdlib.h> int comp(const void *i, const void *j) { int *a= (int *)i; int *b= (int *)j; return a[0]- b[0]; } int main() { int n, i,j, k=0,t,m, a[50000][2], b[50000]; long long int sum=0; scanf("%d", &t); for(m=0; m < t; m++) { sum=0; k=0; scanf("%d", &n); for(i=0; i < n; i++) { scanf("%d", &a[i][0] ); a[i][1]= i; b[i]= a[i][0]; } qsort(a, n, sizeof(int)*2, comp); /* for(i=0; i < n ; i++) { printf("%d %d\n", a[i][0], a[i][1]); }*/ for(j=n-1; j >=0; j--) { for(i=k; i <= a[j][1]; i++) { sum= sum + a[j][0] - b[i] ; } k=i; } printf("%lld\n", sum ); } // scanf("%d"); return 0; } Stock Maximize C++ Solution #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <queue> using namespace std; pair<long long, int> a[50010]; long long sum[50010]; int main() { int t; scanf("%d", &t); while (t--){ int n; scanf("%d", &n); for (int i = 1; i <= n; ++i){ scanf("%lld", &a[i].first); a[i].second = i; } for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + a[i].first; sort(a + 1, a + n + 1, [](pair<long long, int> a, pair<long long, int> b){return a.first > b.first;}); int pos = 1; long long ans = 0; for (int i = 1; i <= n; ++i){ int ind = a[i].second; if (ind < pos) continue; cerr << pos << ' ' << ind << ' ' << (sum[ind - 1] - sum[pos - 1])<< endl; ans += (ind - pos)*a[i].first - (sum[ind - 1] - sum[pos - 1]); pos = ind + 1; } printf("%lld\n", ans); cerr << endl; } return 0; } Stock Maximize C Sharp Solution using System; using System.Linq; namespace StockMax { class Program { static void Main() { var t = Convert.ToInt32(Console.ReadLine()); for (var i = 0; i < t; i++) { var n = Convert.ToInt32(Console.ReadLine()); var prices = Console.ReadLine() .Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); Console.WriteLine(CalcBestProfit(prices)); } } static long CalcBestProfit(int[] prices) { var profit = 0L; var index = 0; while (index < prices.Length) { var sellIndex = FindLocalMax(prices, index); profit += GetPeriodProfit(prices, index, sellIndex); index = sellIndex + 1; } return profit; } static int FindLocalMax(int[] prices, int startFrom) { var max = prices[startFrom]; var index = startFrom; for (var i = startFrom + 1; i < prices.Length; i++) { if (prices[i] > max) { max = prices[i]; index = i; } } return index; } static long GetPeriodProfit(int[] prices, int fromIndex, int toIndex) { if (fromIndex == toIndex) return 0; var profit = 0L; for (var i = fromIndex; i < toIndex; i++) { profit += prices[toIndex] - prices[i]; } return profit; } } } Stock Maximize Java Solution import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { /* * Complete the 'stockmax' function below. * * The function is expected to return a LONG_INTEGER. * The function accepts INTEGER_ARRAY prices as parameter. */ public static long stockmax(List<Integer> prices) { // Write your code here long currPrice = 0; int leftPtr = 0; int currMaxIndex = findMaxIndex(prices, leftPtr, prices.size() - 1); while(currMaxIndex < prices.size()) { for(int i = leftPtr; i < currMaxIndex; i++) { currPrice += -prices.get(i) + prices.get(currMaxIndex); } leftPtr = currMaxIndex + 1; currMaxIndex = findMaxIndex(prices, leftPtr, prices.size() - 1); } return currPrice; } public static int findMaxIndex(List<Integer> list, int startIndex, int endIndex) { int index = startIndex; if (startIndex >= list.size()) { return list.size(); } for(int i = startIndex; i <= endIndex; i++) { if (list.get(i) > list.get(index)) { index = i; } } return index; } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int t = Integer.parseInt(bufferedReader.readLine().trim()); IntStream.range(0, t).forEach(tItr -> { try { int n = Integer.parseInt(bufferedReader.readLine().trim()); List<Integer> prices = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()); long result = Result.stockmax(prices); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); } catch (IOException ex) { throw new RuntimeException(ex); } }); bufferedReader.close(); bufferedWriter.close(); } } Stock Maximize JavaScript Solution function processData(input) { var args = input.split(/\n/); var t = Number(args[0]); var i; var cases = []; function toArray(input, del) { del = del === undefined ? ' ' : del; return input.split(del).map(function(n) { return parseInt(n); }); } args = args.slice(1); for (i = 0; i < t; i++) { cases.push(toArray(args[i * 2 + 1])); } cases.forEach(function(_case) { var result = maximize(_case); console.log(result); }); function maximize(stocks) { var maxStockIndex = stocks.length - 1; var localProfit = 0; var totalProfit = 0; for (i = stocks.length - 2; i >= 0; i--) { if (stocks[i] < stocks[maxStockIndex]) { localProfit = localProfit + stocks[maxStockIndex] - stocks[i]; } else { totalProfit += localProfit; maxStockIndex = i; localProfit = 0; } } totalProfit += localProfit; return totalProfit; } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); Stock Maximize Python Solution def calc(prices): max_next_price = [0]*len(prices) max_next = 0 # figure out what the maximum next price will be for each day for i in reversed(range(len(prices))): # reversed(enumerate(prices)): -- would need to expand generator with list() - not good if prices[i] > max_next: max_next = prices[i] max_next_price[i] = max_next balance = 0 shares = 0 for (i,v) in enumerate(prices): if max_next_price[i] > v: # buy! balance -= v shares += 1 elif max_next_price[i] == v: # sell all balance += shares * v shares = 0 else: pass return balance def read_ints(): return [int(x) for x in input().strip().split()] T = int(input()) for tc in range(T): N = int(input()) prices = read_ints() profit = calc(prices) print(profit) c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython