fork download
  1. import java.util.Arrays;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int n = 5; // size of the array
  6. int[] a = {6, 7, 3, 2, 2};
  7.  
  8. int[] dp = new int[n + 1]; // dp array
  9. int i = 0;
  10. while (i <= n - 1) {
  11. if (i == 0) {
  12. dp[i] = a[i];
  13. } else {
  14. dp[i] = a[i] + dp[i - 1];
  15. }
  16. i++;
  17. }
  18.  
  19. int q = 4; // number of queries
  20. int[] w = {0, 3, 4, 2}; // query array
  21. i = 0;
  22. while (i <= q - 1) {
  23. int query = w[i];
  24. System.out.println(dp[query]); // answering each query in O(1)
  25. i++;
  26. }
  27. }
  28. }
Success #stdin #stdout 0.1s 54644KB
stdin
Standard input is empty
stdout
6
18
20
16