Skip to content

Commit

Permalink
Adds sorting example and prefix sum
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Dec 29, 2023
1 parent 645085e commit 3e7dbfd
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
51 changes: 51 additions & 0 deletions 2389.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from typing import List
import unittest
import itertools
import bisect


class Solution:
# def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
# result: List[int] = []
# numsSize = len(nums)

# for query in queries:
# total, i = 0, 0
# while i < numsSize and (total + nums[i] <= query):
# total += nums[i]
# i += 1

# result.append(i)

# return result

def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
"""Prefix sum approach: it uses itertools.accumulate to create a new
list with the result of accumulation of previous + current item.
Than it uses bisect.bisect_right to find the next index of greater number of n.
"""
nums.sort()
numsSum = list(itertools.accumulate(nums))
return [bisect.bisect_right(numsSum, n) for n in queries]


class Test(unittest.TestCase):
def setUp(self):
self.solution = Solution()

def test_first(self):
self.assertEqual(
self.solution.answerQueries(nums=[1, 2, 4, 5], queries=[3, 10, 21]),
[2, 3, 4],
)

def test_second(self):
self.assertEqual(
self.solution.answerQueries(nums=[2, 3, 4, 5], queries=[1]),
[0],
)


if __name__ == "__main__":
unittest.main()
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
| 2363.py | | |
| 2367-2.py | | |
| 2367.py | | |
| 2389.py | Soring/PrefixSum | https://leetcode.com/problems/longest-subsequence-with-limited-sum |
| 2418.py | | |
| 2475.py | | |
| 2500.py | | |
Expand Down

0 comments on commit 3e7dbfd

Please sign in to comment.