HackerRank Java Arrays- Array Manipulation




Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.



  1. import java.io.*;
  2. import java.math.*;
  3. import java.security.*;
  4. import java.text.*;
  5. import java.util.*;
  6. import java.util.concurrent.*;
  7. import java.util.regex.*;
  8. public class Solution {
  9. public static void main(String[] args) {
  10. Scanner scan = new Scanner(System.in);
  11. int N = scan.nextInt();
  12. int M = scan.nextInt();
  13. /* Save interval endpoints' "k" values in array */
  14. long [] array = new long[N + 1];
  15. while (M-- > 0) {
  16. int a = scan.nextInt();
  17. int b = scan.nextInt();
  18. int k = scan.nextInt();
  19. array[a-1] += k;
  20. array[b] -= k; // see comment at end of code
  21. }
  22. scan.close();
  23. /* Find max value */
  24. long sum = 0;
  25. long max = 0;
  26. for (int i = 0; i < N; i++) {
  27. sum += array[i];
  28. max = Math.max(max, sum);
  29. }
  30. System.out.println(max);
  31. }
  32. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution


download android app

Popular HackerRank Arrays-java Solutions








codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube