fork download
  1. import java.util.*;
  2.  
  3. class Ideone {
  4. public static void main(String[] args) throws java.lang.Exception {
  5. Scanner sc = new Scanner(System.in);
  6. int n = 5; // Size of the array
  7. int[] arr = new int[n]; // Initialize the array
  8.  
  9. // Input array elements
  10. for (int i = 0; i < n; i++) {
  11. arr[i] = sc.nextInt();
  12. }
  13.  
  14. int b = sc.nextInt(); // Read the number of selections allowed
  15.  
  16. // If the number of selections exceeds half the array size, return -1
  17. if (b > (n / 2) + 1) {
  18. System.out.print(-1);
  19. return;
  20. }
  21.  
  22. int left = 0; // Pointer for the left side of the array
  23. int right = n - 1; // Pointer for the right side of the array
  24. int sum = 0; // Variable to store the sum
  25.  
  26. // While we have selections left
  27. while (b > 0) {
  28. // Compare the leftmost and rightmost elements
  29. if (arr[left] > arr[right]) {
  30. sum += arr[left]; // Take the left element
  31. left++; // Move the left pointer to the right
  32. } else {
  33. sum += arr[right]; // Take the right element
  34. right--; // Move the right pointer to the left
  35. }
  36. b--; // Decrease the number of selections left
  37. }
  38.  
  39. System.out.print(sum); // Output the maximum sum
  40. }
  41. }
  42.  
Success #stdin #stdout 0.18s 56592KB
stdin
6 -2 3 4 5
3
stdout
15