Skip to content

Update 0494-target-sum.py (runtime and memory > 80%) #2296

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

purnawirman
Copy link

File(s) Modified: 0494-target-sum.py
Language(s) Used: _python
Submission URL: https://leetcode.com/problems/target-sum/submissions/905306462/

optimize more by:

  1. using only 2 rows of dp
  2. iterate only on non zero previous row dp

optimize more by:
1. using only 2 rows of dp
2. iterate only on non zero previous row dp
Target sum (runtime and memory > 80%)
@purnawirman purnawirman changed the title Target sum (runtime and memory > 80%) #1 Update 0494-target-sum.py (runtime and memory > 80%) Feb 26, 2023
@raul-sauco
Copy link
Contributor

Same idea but using a Counter makes it a bit more readable, in my opinion, and the performance is similar.

Runtime 304 ms Beats 87.41%
Memory 14.1 MB Beats 88.17%

https://leetcode.com/problems/target-sum/submissions/842843238/

class Solution:
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        dp = Counter([0])
        for num in nums:
            next = Counter()
            for key in dp.keys():
                next[key - num] += dp[key]
                next[key + num] += dp[key]
            dp = next
        return dp[target]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants