prefix-sum:

Contiguous Array

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1 Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Example 2 Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. Note The length of the given binary array will not exceed 50,000.

by lek tin in "algorithm" access_time 1-min read

Maximum Value Array M Range Increment Operations

Consider an array of size n with all initial values as 0, we need to perform following m range increment operations. increment(a, b, k) : Increment values from a to b by k. After m operations, we need to calculate the maximum of the values in the array. Example 1 Input : n = 5 m = 3 a = 0, b = 1, k = 100 a = 1, b = 4, k = 100 a = 2, b = 3, k = 100 Output : 200 Explanation: Initially array = {0, 0, 0, 0, 0} After first operation: array = {100, 100, 0, 0, 0} After second operation: array = {100, 200, 100, 100, 100} After third operation: array = {100, 200, 200, 200, 100} Maximum element after m operations is 200.

by lek tin in "algorithm" access_time 2-min read

Subarray Sum Equals K

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1 «««< HEAD dev Input:nums = [1,1,1], k = 2 Output: 2 Note The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

by lek tin in "algorithm" access_time 2-min read

Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. Solution (Dynamic Programming) class Solution { public int maxSubArray(int[] nums) { if (nums.

by lek tin in "algorithm" access_time 2-min read