327. Count of Range Sum (Solution 1)

package LeetCode_327

/**
 * 327. Count of Range Sum
 * https://leetcode.com/problems/count-of-range-sum/
 * Given an integer array nums and two integers lower and upper, 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 inclusive, where i <= j.

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

Example 2:
Input: nums = [0], lower = 0, upper = 0
Output: 1

Constraints:
1. 1 <= nums.length <= 105
2. -231 <= nums[i] <= 231 - 1
3. -105 <= lower <= upper <= 105
4. The answer is guaranteed to fit in a 32-bit integer.
 * */
class Solution {
    /**
     * solution 1: Accumulative array, then check sum of range if correct, TLE: 61/67 test cases passed; Time:O(n^2), Space:O(n)
     * solution 2: Merge sort, O(nlogn)
     * */
    fun countRangeSum(nums: IntArray, lower: Int, upper: Int): Int {
        var result = 0
        val size = nums.size
        val dp = LongArray(size)
        dp[0] = nums[0].toLong()
        for (i in 1 until size) {
            dp[i] = nums[i] + dp[i - 1]
        }
        for (i in 0 until size) {
            for (j in 0 until size) {
                if (i > j) {
                    //where i <= j
                    continue
                }
                val curSum = sumRange(dp, i, j)
                if (curSum in lower..upper) {
                    result++
                }
            }
        }
        return result
    }

    private fun sumRange(dp: LongArray, i: Int, j: Int): Long {
        val sum = if (i == 0) dp[j] else dp[j] - dp[i - 1]
        return sum
    }
}
原文地址:https://www.cnblogs.com/johnnyzhao/p/15086345.html