fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6.  
  7. // Read the number of elements
  8. int n = scanner.nextInt();
  9. // Initialize arrays to store values, prefix sums, and maximums
  10. int[] b = new int[n + 1]; // Original array
  11. int[] p = new int[n + 1]; // Array to store maximum prefix sums
  12. int[] s = new int[n + 1]; // Array to store sums of increasing sequences
  13. int[] u = new int[n + 1]; // Array to store maximum values at each index
  14. int[] max_s = new int[n + 1]; // Array to store maximum sums from index i to n
  15.  
  16. // Input the values into the array b
  17. for (int i = 1; i <= n; i++) {
  18. b[i] = scanner.nextInt();
  19. }
  20.  
  21. // Calculate the maximum prefix sums
  22. // p[i] will store the maximum sum of subarrays ending at index i
  23. p[1] = b[1]; // Base case: the first element is the only subarray
  24. for (int i = 2; i <= n; i++) {
  25. // Either take the current element or extend the previous maximum sum
  26. p[i] = Math.max(b[i], p[i - 1] + b[i]);
  27. }
  28.  
  29. // Initialize the last elements for further calculations
  30. s[n] = b[n]; // Start with the last element
  31. u[n] = s[n]; // Initialize u[n] as well
  32.  
  33. // Calculate sums of increasing sequences and their maximums
  34. for (int j = n - 1; j >= 1; j--) {
  35. // If the current element is less than the next, add to the sum
  36. if (b[j] < b[j + 1]) {
  37. s[j] = b[j] + s[j + 1]; // Extend the increasing sequence
  38. } else {
  39. s[j] = b[j]; // Start a new sequence
  40. }
  41.  
  42. // Store the maximum value between the current element and the sum
  43. u[j] = Math.max(b[j], s[j]);
  44. // Update the maximum sums from index j to n
  45. max_s[j] = Math.max(u[j], max_s[j + 1]);
  46. }
  47.  
  48. // Variable to store the final answer
  49. int answer = 0;
  50.  
  51. // Calculate the maximum possible sum by combining prefix sums and maximum suffix sums
  52. for (int i = 1; i <= n - 1; i++) {
  53. // Combine the maximum prefix sum up to i and the maximum suffix sum from i+1
  54. int l = p[i] + max_s[i + 1];
  55. // Update the answer if the current combination is larger
  56. answer = Math.max(answer, l);
  57. }
  58.  
  59. // Output the final answer
  60. System.out.println(answer);
  61. }
  62. }
  63.  
Success #stdin #stdout 0.1s 54548KB
stdin
5
5 -8 1 1 5
stdout
11