fork download
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.StringTokenizer;
  5.  
  6. class FastReader {
  7.  
  8. public FastReader() {
  9. }
  10.  
  11. String next() throws IOException {
  12. while (st == null || !st.hasMoreElements()) {
  13. st = new StringTokenizer(br.readLine());
  14. }
  15. return st.nextToken();
  16. }
  17.  
  18. int nextInt() throws IOException {
  19. return Integer.parseInt(next());
  20. }
  21.  
  22. long nextLong() throws IOException {
  23. return Long.parseLong(next());
  24. }
  25.  
  26. double nextDouble() throws IOException {
  27. return Double.parseDouble(next());
  28. }
  29.  
  30. String nextLine() throws IOException{
  31. return br.readLine();
  32. }
  33. }
  34.  
  35. class Main{
  36. static class Node{
  37. long prefix, suffix;
  38. long max;
  39. long sum;
  40. Node(int s){
  41. prefix = suffix = max = sum = s;
  42. }
  43. }
  44.  
  45. public static void build(int ind, int l, int r){
  46. if( l==r){
  47. segment[ind] = new Node(ar[l]);
  48. return;
  49. }
  50. int mid = l+ (r-l)/2;
  51. build(2*ind+1, l, mid);
  52. build(2*ind+2, mid+1, r);
  53.  
  54. segment[ind] = new Node(0);
  55. calulate(segment[ind], segment[2*ind+1], segment[2*ind+2]);
  56. }
  57. public static void calulate(Node res, Node left, Node right){
  58. res.prefix = Math.max(left.prefix, left.sum+ right.prefix);
  59. res.suffix = Math.max(right.suffix, right.sum+ left.suffix);
  60. res.max = Math.max(Math.max(left.max, right.max), left.suffix+right.prefix);
  61. res.sum = left.sum + right.sum;
  62. res.max = Math.max(res.max, res.prefix);
  63. res.max = Math.max(res.max, res.suffix);
  64. res.max = Math.max(res.max, res.sum);
  65. }
  66.  
  67. public static Node query(int ind, int l, int r, int ql, int qr){
  68. Node res = new Node(0);
  69. if( r < ql || qr < l){
  70. return res;
  71. }
  72. if( ql <= l && qr >= r){
  73. return segment[ind];
  74. }
  75. int mid = l+ (r-l)/2;
  76. Node left = query(2*ind+1, l, mid, ql ,qr);
  77. Node right = query(2*ind+2, mid+1, r, ql ,qr);
  78. calulate(res, left, right);
  79. return res;
  80. }
  81. static int[] ar;
  82. static Node[] segment;
  83. public static void main(String[] args) throws IOException {
  84. FastReader ff = new FastReader();
  85. int n = ff.nextInt();
  86. ar = new int[n];
  87. segment = new Node[(4*n)+5];
  88. for(int i = 0; i < n; i++){
  89. ar[i] = ff.nextInt();
  90. }
  91. build(0, 0, n-1);
  92. int q = ff.nextInt();
  93.  
  94. while(q-- > 0){
  95. int l = ff.nextInt()-1;
  96. int r = ff.nextInt()-1;
  97. System.out.println(query(0, 0, n - 1, l, r).max);
  98. }
  99. }
  100. }
Success #stdin #stdout 0.08s 47808KB
stdin
3 
-1 2 3
1
1 2
stdout
2