Skip to content

Commit

Permalink
Adds two other sorting exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Dec 12, 2023
1 parent 78fd224 commit 6f79929
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
38 changes: 38 additions & 0 deletions 1464.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from typing import List
import unittest


class Solution:
# O(nlog(n)) approach where we sort the array to find the two biggest values
# def maxProduct(self, nums: List[int]) -> int:
# nums.sort()
# return (nums[-2] - 1) * (nums[-1] - 1)

# O(n) approach where we iterate over the list to find what are the two biggest values
def maxProduct(self, nums: List[int]) -> int:
num1 = 0
num2 = 0

for n in nums:
if n > num1:
num2 = num1
num1 = n
else:
num2 = max(n, num2)

return (num1 - 1) * (num2 - 1)


class Test(unittest.TestCase):
def test_first(self):
self.assertEqual(Solution().maxProduct(nums=[3, 4, 5, 2]), 12)

def test_second(self):
self.assertEqual(Solution().maxProduct(nums=[1, 5, 4, 5]), 16)

def test_third(self):
self.assertEqual(Solution().maxProduct(nums=[10, 11]), 90)


if __name__ == "__main__":
unittest.main()
44 changes: 44 additions & 0 deletions 1710.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from typing import List
import unittest

# https://leetcode.com/problems/maximum-units-on-a-truck/


class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
count = 0

boxTypes.sort(key=lambda box: box[1], reverse=True)

for types in boxTypes:
boxes = types[0]
amount = types[1]

if truckSize - boxes >= 0:
count += boxes * amount
truckSize -= boxes
else:
boxes = boxes - abs(truckSize - boxes)
count += boxes * amount
truckSize -= boxes

return count


class Test(unittest.TestCase):
def test_first(self):
self.assertEqual(
Solution().maximumUnits(boxTypes=[[1, 3], [2, 2], [3, 1]], truckSize=4), 8
)

def test_second(self):
self.assertEqual(
Solution().maximumUnits(
boxTypes=[[5, 10], [2, 5], [4, 7], [3, 9]], truckSize=10
),
91,
)


if __name__ == "__main__":
unittest.main()

0 comments on commit 6f79929

Please sign in to comment.