Showing posts with label divide and conquer. Show all posts
Showing posts with label divide and conquer. Show all posts

Monday, January 11, 2016

LeetCode [327] Count of Range Sum

327. Count of Range Sum
Hard

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.

Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.

Example:

Input: nums = [-2,5,-1], lower = -2, upper = 2,
Output: 3 
Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2.

 

Constraints:

  • 0 <= nums.length <= 10^4
//C++
//C++: TLE Divide and Conquer
class Solution {
public:
    int countRangeSum(vector<int>& nums, int lower, int upper) {
        if(nums.empty() || lower>upper) return 0;
        int n = nums.size();
        if(n==1) return nums[0]>=lower&&nums[0]<=upper?1:0;
        vector<int> left(nums.begin(), nums.begin()+n/2);
        vector<int> right(nums.begin()+n/2, nums.end());
        int nl = countRangeSum(left, lower, upper);
        int nr = countRangeSum(right, lower, upper);

        for(int i=left.size()-2; i>=0; --i){
            left[i] += left[i+1];
        }
        for(int i=1; i<right.size(); ++i){
            right[i] += right[i-1];
        }
        sort(right.begin(), right.end());

        int c = 0;
        for(auto e:left){
            int a = lower-e, b = upper-e;
            int l = 0, r = right.size()-1;
            while(l<=r){
                if(right[l]<a){
                    l++;
                }else if(right[r]>b){
                    r--;
                }else{
                    break;
                }
            }
            c += r-l+1;
        }
        return c+nl+nr;
    }
};
]]></script>

<script class="brush: js" type="syntaxhighlighter"><![CDATA[
//C++: 72ms
typedef long long ll;

class Solution {
public:
    vector<ll> dm(vector<ll> nums, int lower, int upper, int &ret){
        int n = nums.size();
        if(n<2) return nums;
        vector<ll> left = dm(vector<ll>(nums.begin(), nums.begin()+n/2), lower, upper, ret);
        vector<ll> right = dm(vector<ll>(nums.begin()+n/2, nums.end()), lower, upper, ret);
        int nl = left.size(), nr = right.size(), t = 0, i = 0, j = 0, k = 0, index=-1;
        vector<ll> merge(n);
        for(; i<nl; ++i){
            while(j<nr && right[j]-left[i]<lower) j++;
            while(k<nr && right[k]-left[i]<=upper) k++;
            ret += k-j;
            while(t<nr && right[t]<=left[i]){
                merge[++index] = right[t++];
            }
            merge[++index] = left[i];
        }
        while(index<n-1){
            merge[++index] = right[t++];
        }
        return merge;
    }


    int countRangeSum(vector<int>& nums, int lower, int upper) {
        int ret = 0, n =  nums.size()+1;
        vector<ll> sums(n, 0);
        for(int i=1; i<n; ++i) sums[i] = sums[i-1] + nums[i-1];
        dm(sums, lower, upper, ret);
        return ret;
    }
};
//Java
class Solution {
    public int countRangeSum(int[] nums, int lower, int upper) {
        int n = nums.length;
        long[] array = new long[n+1];
        for(int i=1; i<=n; ++i){
            array[i] = array[i-1] + nums[i-1];
        }
        return helper(array, 0, n, lower, upper);
    }

    int helper(long[] array, int start, int end, int lower, int upper){
        if(end-start+1<2) return 0;
        int mid = (start+end)/2, count = 0;
        count += helper(array, start, mid, lower, upper);
        count += helper(array, mid+1, end, lower, upper);

        int j = mid+1, k = mid+1, l = mid+1, m = 0;
        long[] cache = new long[end-start+1];
        for(int i=start; i<=mid; ++i){
            while(j<=end && array[j]-array[i]<lower) j++;
            while(k<=end && array[k]-array[i]<=upper) k++;
            count += k-j;
            while(l<=end && array[l]<=array[i]) cache[m++] = array[l++];
            cache[m++] = array[i];
        }

        System.arraycopy(cache, 0, array, start, m);
        return count;
    }
}

Tuesday, September 15, 2015

LeetCode [282] Expression Add Operators

282. Expression Add Operators
Hard

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.

Example 1:

Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"] 

Example 2:

Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]

Example 3:

Input: num = "105", target = 5
Output: ["1*0+5","10-5"]

Example 4:

Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]

Example 5:

Input: num = "3456237490", target = 9191
Output: []

 

Constraints:

  • 0 <= num.length <= 10
  • num only contain digits.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
typedef long long ll;
class Solution {
public:
    vector<string> addOperators(string num, int target) {
        vector<string> ret;
        dfs(num, "", 0, 0, 0, ret, target);
        return ret;
    }

    void dfs(string num, string exp, int pos, ll curVal, ll preVal, vector<string>& ret, ll target)
    {
        if(pos == num.size() && curVal==target)
        {
            ret.push_back(exp);
        }
        else if(pos<num.size())
        {
            for(int i=pos; i<num.size(); ++i)
            {
                string v = num.substr(pos, i-pos+1);
                if(v.size()>1 && v[0]=='0') break;
                if(pos==0)
                {
                    dfs(num, v, i+1, stoll(v), stoll(v), ret, target);
                }
                else
                {
                    dfs(num, exp+"+"+v, i+1, curVal+stoll(v), stoll(v), ret, target);
                    dfs(num, exp+"-"+v, i+1, curVal-stoll(v), -stoll(v), ret, target);
                    dfs(num, exp+"*"+v, i+1, curVal-preVal+preVal*stoll(v), preVal*stoll(v), ret, target);
                }
                
            }
        }
    }
};

Wednesday, July 22, 2015

LeetCode [240] Search a 2D Matrix II

 240. Search a 2D Matrix II

Medium

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size();
        if(m==0) return 0;
        int n = matrix[0].size();
        if(n==0) return 0;
        int i = 0, j = n-1;
        while(i<m && j>=0){
            if(target==matrix[i][j]) return true;
            if(target<matrix[i][j]) j--;
            else i++;
        }
        return false;
    }
};

Wednesday, February 4, 2015

LeetCode [53] Maximum Subarray

 53. Maximum Subarray

Easy

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

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.

 

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [0]
Output: 0

Example 4:

Input: nums = [-1]
Output: -1

Example 5:

Input: nums = [-2147483647]
Output: -2147483647

 

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -231 <= nums[i] <= 231 - 1
//C++
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int n = nums.size();
        vector<int> dp(n, 0);
        int ret = INT_MIN;
        for(int i=0; i<n; ++i){
            if(i==0){
                dp[i] = nums[i];
            }else{
                dp[i] = max(dp[i-1]+nums[i], nums[i]);
            }
            ret = max(ret, dp[i]);
        }
        return ret;
    }
};

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int max_ending_here = INT_MIN;
        int max_so_far = INT_MIN;
        for(auto n:nums){
            if(max_ending_here<0) max_ending_here = 0;
            max_ending_here += n;
            max_so_far = max(max_so_far, max_ending_here);
        }
        return max_so_far;
    }
};

class Solution {
public:
    int maxSubArray(vector<int>& nums, int l, int m, int r){
        int sum = 0;
        int left = INT_MIN;
        for(int i=m; i>=l; --i){
            sum += nums[i];
            left = max(left, sum);
        }
        
        sum = 0;
        int right = INT_MIN;
        for(int i=m+1; i<=r; ++i){
            sum += nums[i];
            right = max(right, sum);
        }        
        return left+right;
    }

    int maxSubArray(vector<int>& nums, int l, int r){
        if(l>r) return 0;
        if(l==r) return nums[l];
        int m = (l+r)/2;
        int left = maxSubArray(nums, l, m);
        int right = maxSubArray(nums, m+1, r);
        int cross = maxSubArray(nums, l, m, r);
        return max(left, max(right, cross));
    }
    
    int maxSubArray(vector<int>& nums) {
        return maxSubArray(nums, 0, nums.size()-1);
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int maxSum = Integer.MIN_VALUE;
        int[] dp = new int[n];//local optimal ending(including) at i
        for(int i=0; i<n; ++i){
            dp[i] = nums[i];
            if(i>0 && dp[i]<dp[i-1]+nums[i]){
                dp[i] = dp[i-1]+nums[i];
            }
            maxSum = Math.max(maxSum, dp[i]);
        }
        return maxSum;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int maxSum = Integer.MIN_VALUE;
        int prev = 0;//local optimal
        for(int i=0; i<n; ++i){
            int cur = nums[i];
            if(i>0 && cur<prev+nums[i]){
                cur = prev+nums[i];
            }
            maxSum = Math.max(maxSum, cur);
            prev = cur;
        }
        return maxSum;
    }
}

YMSF

Given an array containing only 0 and 1s, find the best subarray to perform a single flip operation. The goal is that: after the flip, number of 1s should  be the maximum.

Flip operation means that you will convert all 0 to 1, and all 1 to 0 in that array.

You can skip flipping if you think it is not worth doing the flip.

Return the maximum number of 1s after you do the flip.


队友还是用的prefix sum再找区间最大的差值,面试官说可以O(1)空间,作为homework。


Follow-up: what if it is a 2D array?


第二轮,考虑flip 0的收益是1,flip 1的收益是-1,问题转化为【求一个element是1或者-1的array的max subarray sum】,直接slide window就可以了。等价于leetcode 53。(一个小区别是这里可以选择empty subarray)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package Flip01;

public class Main {
    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] arr = new int[]{0,0,1,0,0};
        int r = sol.getMax1(arr);
        System.out.println(r);
    }
}

class Solution{
    int getMax1(int[] arr){
        int n = arr.length;
        int max1s = 0;
        int prevFlip = 1-arr[0];
        int prevNotFlip = arr[0];

        for(int i=1; i<n; ++i){
            int curNotFlip = Math.max(arr[i], prevNotFlip + arr[i]);
            int curFlip = Math.max(1-arr[i], prevFlip + 1-arr[i]);
            max1s = Math.max(max1s, Math.max(curNotFlip, curFlip));
            prevFlip = curFlip;
            prevNotFlip = curNotFlip;
        }

        return max1s;
    }
}