fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.Collectors;
  7. import java.util.stream.IntStream;
  8. import java.util.stream.Stream;
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. List<Integer> numbers = Arrays.asList(5,10,4,-1);
  15. Ideone mm = new Ideone();
  16. int maxi = mm.maximumm(numbers);
  17. System.out.println(maxi);
  18. }
  19.  
  20. public int maximumm(List<Integer> numbers) {
  21. int toIndex = 3, fromIndex = 0;
  22. List<Integer> result = new ArrayList<>();
  23. while (toIndex < numbers.size()) {
  24. Map<Integer, Integer> map = IntStream
  25. .range(fromIndex, toIndex)
  26. .filter(i->numbers.get(i)>0)
  27. .mapToObj(i -> new AbstractMap.SimpleEntry<>(i, numbers.get(i)))
  28. .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey,(a,b)->a));
  29. // find max of sublist
  30. int maxOfSub = numbers.subList(fromIndex, toIndex).stream().max(Integer::compareTo).get();
  31. //update indexes
  32. fromIndex = map.getOrDefault(maxOfSub,toIndex-1) + 2;
  33. toIndex += fromIndex;
  34.  
  35. if (maxOfSub > 0)
  36. result.add(maxOfSub);
  37. }
  38. int lastMax = numbers.subList(fromIndex, numbers.size()).stream().max(Integer::compareTo).get();
  39. if (lastMax > 0)
  40. result.add(lastMax);
  41. System.out.println(result);
  42. return result.stream().reduce(0,Integer::sum);
  43. }
  44. }
Success #stdin #stdout 0.15s 2184192KB
stdin



stdout
[10]
10