C# solution: sums array


  • 0
    B
    public class Solution 
    {
        public int SubarraySum(int[] nums, int k) 
        {
            if (nums.Length == 0) return 0;
    
            var n = nums.Length;
            var sums = new int[n];
    
            var result = 0;
    
            for(int i = 0; i < n; i++)
            {
                if (i == 0) sums[i] = nums[i];
                else  sums[i] = sums[i-1] + nums[i];
    
                if (sums[i] == k) result++;
            }
    
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    if (sums[i] - sums[j] == k) result++;
                }
            }
    
            return result;
    
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.