forked from lothar.buchholz/buy-and-sell-twice
stream solution for two sales
parent
c86c1ba120
commit
2cb56d6ee4
@ -1,20 +1,36 @@
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.io.*;
|
import java.util.stream.IntStream;
|
||||||
import java.math.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Template code to help you parse the standard input
|
|
||||||
* according to the problem statement.
|
|
||||||
**/
|
|
||||||
class Solution {
|
class Solution {
|
||||||
|
|
||||||
public static void main( String[] args ) {
|
public static void main( String[] args ) {
|
||||||
Scanner in = new Scanner( System.in );
|
|
||||||
// read values with in.next...() methods
|
// read values with in.next...() methods
|
||||||
|
var prices = new Scanner( System.in ).tokens()
|
||||||
|
.mapToInt( Integer::valueOf )
|
||||||
|
.toArray();
|
||||||
|
|
||||||
// code your solution here
|
// code your solution here
|
||||||
|
var maxSum = IntStream.range( 2, prices.length - 1 )
|
||||||
|
.map( sellIndex -> {
|
||||||
|
var firstRange = Arrays.copyOfRange( prices, 0, sellIndex );
|
||||||
|
var secondRange = Arrays.copyOfRange( prices, sellIndex - 1, prices.length );
|
||||||
|
return maxProfit( firstRange ) + maxProfit( secondRange );
|
||||||
|
})
|
||||||
|
.max().orElse( 0 );
|
||||||
|
|
||||||
// Write result with System.out.println()
|
// Write result with System.out.println()
|
||||||
System.out.println( "value" );
|
System.out.println( maxSum );
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static int maxProfit( int[] prices ){
|
||||||
|
return IntStream.range( 0, prices.length )
|
||||||
|
.map( index -> {
|
||||||
|
var range = Arrays.copyOfRange( prices, index, prices.length );
|
||||||
|
var max = IntStream.of( range ).max().orElse( 0 );
|
||||||
|
// difference between current price and future maximum
|
||||||
|
return max - prices[index];
|
||||||
|
})
|
||||||
|
.max().orElse( 0 );
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue