Is this really an "easy" problem


  • 18
    G

    It took me much more time to solve this question than any other "Easy" problem.
    I think that who ever classified this problem as easy made a mistake.
    This is a medium level question. What makes this question harder, is the handling of 0.


  • 1
    A

    It accepts obvious O(N^2) solution, so I think that yes, it can be considered as easy problem


  • 1
    S

    No it doesn't accept an O(N^2) solution.


  • 0
    A

    Well, maybe I was lucky, but that one passed all tests and was marked as accepted.

    public class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
    int len = 0;
    for (int i=0; i<nums.length; i++) {
    int sum = 0;
    for (int j=i; j<nums.length; j++) {
    sum += nums[j];
    if(sum == k) {
    len = Math.max(len, j-i+1);
    }
    }
    }

        return len;
    }
    

    }


  • 0
    S

    Maybe at that point the time limits were not added, I will add my solution at the bottom with code formatting.


  • 0
    S

    Based on the comments below O(N^2) solution - doesn't get accepted - by this I am in noway implying the problem is hard or not :).

    int maxSubArrayLen(vector<int>& nums, int k) {
    	int len = nums.size(); if (len == 0) return 0;
    	int maxLen = INT_MIN, steps = 0, sum = 0;
    	for (int i = 0; i < len; ++i)
    	{
    		sum = nums[i];
    		for (int j = i + 1; j < len; ++j)
    		{
    			sum += nums[j];
    			if (sum == k) maxLen = max(maxLen, j - i + 1);
    		}
    	}
    	return maxLen == INT_MIN ? 0 : maxLen;
    }

  • 0
    S

    I have similar solution at first. Just have two questions for your code:

    1. It seems that your checking for "len == 0" and variable "steps" are not necessary.

    2. What about the case: nums = {1}, k = 1? It seems that your code will return 0?


  • 0
    S
    1. len == 0 is not required true, steps is just a copy/paste foobar
    2. true, it needs a condition on len == 1 and k == element

Log in to reply
 

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