Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหาจำนวนงานที่เสร็จสิ้นได้ภายใต้เงื่อนไขใน Python

ให้ลิสต์ tasks (strength ที่ต้องการ) และ people (strength ของแต่ละคน) คนละ 1 งาน หางานที่ทำได้สูงสุด

ตัวอย่าง: tasks=[4,3,9,15], people=[10,5,3,2] → 3 (คน1 ทำ 9, คน2 ทำ 4, คน3 ทำ 3)

อัลกอริธึม Greedy + Sorting

  • เรียง tasks และ people จากน้อยไปมาก
  • คนแต่ละคน (จาก strength น้อยไปมาก) มอบงานที่ต้องการ strength น้อยที่สุดที่ทำได้

การนำไปใช้

class Solution:
    def solve(self, tasks, people):
        tasks.sort()
        people.sort()
        ct = ind = 0
        for p in people:
            for j in range(ind, len(tasks)):
                if p >= tasks[j]:
                    ct += 1
                    ind += 1
                    break
                else:
                    break
        return ct

ob = Solution()
print(ob.solve([4,3,9,15], [10,5,3,2]))  # 3