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.
Array Manipulation
Array Manipulation
+ 1 comment // Write your code here. Can someone help to optimize the below code ? Time limit exceeding for some testcases. Rest all passed
List<Long> li = new ArrayList<>(); for(int i = 0;i<n;i++){ li.add(0L); } for(int i = 0;i<queries.size();i++){ int temp1 = queries.get(i).get(0); int temp2 = queries.get(i).get(1); int k = queries.get(i).get(2); for(int a = temp1-1;a<=temp2-1;a++){ li.set(a,li.get(a)+k); } } long max = li.get(0); for(int i=1;i<n;i++){ if(li.get(i)>max){ max = li.get(i); } } return max;
+ 0 comments Can someone help to optimize the below code ? Time limit exceeding for only 7 testcases. Rest all passed
function arrayManipulation(n, queries) { let obj = {}; let max = 0; for (let arr of queries) { for (let i = arr[0] - 1; i < arr[1]; i++) { obj[i] = obj[i] ? (obj[i] += arr[2]) : arr[2]; if (obj[i] > max) max = obj[i]; } } return max; }
+ 1 comment This function passed all tests
def arrayManipulation(n, queries): segments = dict() for a, b, k in queries: segments[a] = segments.get(a, 0) + k segments[b+1] = segments.get(b+1, 0) - k mmax = None val = 0 for i in sorted(segments.keys()): diff = segments[i] if i > n: break val += diff if mmax is None or mmax < val: mmax = val return mmax
+ 1 comment a = [0] * n for _ in range(len(queries)): start = queries[_][0] end = queries[_][1] increment = queries[_][2] for i in range(start,end+1): a [i] = a[i] + increment print(a) maxi = 0; for _ in range(len(a)): if (maxi < a[_]): maxi = a [_] print (maxi)
Wierd: Code works in local machine but hackerranks list index is out of bounds.
+ 0 comments Anyone knows why using a parallel stream results in incorrect results for some tests, even if I use a synchronized list? Shouldn't the list prevent this?
public static long arrayManipulation(int n, List<List<Integer>> queries) { // Write your code here List<Long> sums = Collections.synchronizedList(Arrays.asList(new Long[n + 1])); Collections.fill(sums, 0L); queries.stream().parallel().forEach(query -> { int a = query.get(0); int b = query.get(1); int k = query.get(2); sums.set(a - 1, sums.get(a - 1) + k); sums.set(b, sums.get(b) - k); }); long max = 0; long sum = 0; for (long i : sums.subList(0, n)) { sum += i; max = Math.max(max, sum); } return max; }
Load more conversations
Sort 2280 Discussions, By:
Please Login in order to post a comment