We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
/*
* Complete the 'arrayManipulation' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. 2D_INTEGER_ARRAY queries
*/
public static long arrayManipulation(int n, List<List<Integer>> queries) {
// We use the difference array technique
long[] arr = new long[n + 2]; // n+2 to avoid index issues
for (List<Integer> query : queries) {
int a = query.get(0);
int b = query.get(1);
int k = query.get(2);
arr[a] += k; // add k at start index
arr[b + 1] -= k; // subtract k after end index
}
long max = 0;
long current = 0;
for (int i = 1; i <= n; i++) {
current += arr[i];
if (current > max) {
max = current;
}
}
return max;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
int n = Integer.parseInt(firstMultipleInput[0]);
int m = Integer.parseInt(firstMultipleInput[1]);
List<List<Integer>> queries = new ArrayList<>();
for (int i = 0; i < m; i++) {
String[] queriesRowTempItems = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
List<Integer> queriesRowItems = new ArrayList<>();
for (int j = 0; j < 3; j++) {
int queriesItem = Integer.parseInt(queriesRowTempItems[j]);
queriesRowItems.add(queriesItem);
}
queries.add(queriesRowItems);
}
long result = Result.arrayManipulation(n, queries);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Array Manipulation
You are viewing a single comment's thread. Return to all comments →
import java.io.; import java.util.;
class Result {
}
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
}