You are viewing a single comment's thread. Return to all comments →
How about iterating backwards?
I could solve it with just one loop.
public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); for (int i = 0; i < size; i++) { int numOfDays = scanner.nextInt(); int[] prices = new int[numOfDays]; for (int j = 0; j < numOfDays; j++) { prices[j] = scanner.nextInt(); } System.out.println(getMaxProfit(prices)); } } public static long getMaxProfit(int[] prices) { long profit = 0L; int maxSoFar = 0; for (int i = prices.length - 1; i > -1 ; i--) { if (prices[i] >= maxSoFar) { maxSoFar = prices[i]; } profit += maxSoFar - prices[i]; } return profit; } }
Seems like cookies are disabled on this browser, please enable them to open this website
Stock Maximize
You are viewing a single comment's thread. Return to all comments →
How about iterating backwards?
I could solve it with just one loop.