From 2656ded38f82db00f851733bd74500b06f7cb53f Mon Sep 17 00:00:00 2001 From: Lothar Buchholz Date: Fri, 3 Apr 2020 23:04:12 +0200 Subject: [PATCH] stream solution for n sales --- src/main/java/Solution.java | 57 ++++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 10 deletions(-) diff --git a/src/main/java/Solution.java b/src/main/java/Solution.java index 5615be4..887d93d 100644 --- a/src/main/java/Solution.java +++ b/src/main/java/Solution.java @@ -1,20 +1,57 @@ import java.util.*; -import java.io.*; -import java.math.*; +import java.util.stream.IntStream; -/** - * Template code to help you parse the standard input - * according to the problem statement. - **/ class Solution { public static void main( String[] args ) { - Scanner in = new Scanner( System.in ); // read values with in.next...() methods - - // code your solution here + var scanner = new Scanner( System.in ); + var sellCount = scanner.nextInt(); + var prices = scanner.tokens() + .mapToInt( Integer::valueOf ) + .toArray(); // Write result with System.out.println() - System.out.println( "value" ); + System.out.println( maxProfits( sellCount, prices )); + } + + // code your solution here + // 0 - 1 | ... | x-sellCount - x --> 0 - x-1 | ... | x-1 - x + private static int maxProfits( int sellCount, int[] prices ) { + return IntStream.range( 0, sellCount ) + .parallel() + .map( sale -> { + // recursion end condition + if ( sellCount == 1 ) { + return maxProfit( prices ); + } + else { + return IntStream.range( 2, prices.length ) + .parallel() + .map( index -> { + var firstRange = Arrays.copyOfRange( prices, 0, index ); + final int max1 = maxProfit( firstRange ); + + var secondRange = Arrays.copyOfRange( prices, index - 1, prices.length ); + // reduce range sizes recursively + final int max2 = maxProfits( sellCount - 1, secondRange ); + + return max1 + max2; + }).max().orElse( 0 ); + } + }) + .max().orElse( 0 ); } + + private static int maxProfit( int[] prices ){ + return IntStream.range( 0, prices.length ) + .map( index -> { + var range = Arrays.copyOfRange( prices, Math.min( index + 1, prices.length - 1 ), prices.length ); + int max = IntStream.of( range ).max().orElse( 0 ); + // difference between current price and future maximum + return max - prices[index]; + }) + .max().orElse( 0 ); + } + }