ปัญหา
ให้อาร์เรย์ nums ตรวจสอบว่ามีสมาชิกตัวใดตัวหนึ่งที่มีค่าเท่ากับผลรวมของสมาชิกอื่นทั้งหมดหรือไม่
ตัวอย่าง
nums = [3,2,10,4,1] → 10 = 3+2+4+1 → True
แนวคิดการแก้ปัญหา
- คำนวณผลรวมทั้งหมด
total - ถ้า
totalเป็นเลขคู่ และมีสมาชิกเท่ากับtotal/2→True - เพราะถ้า x = sum(others) → total = x + x = 2x → x = total/2
โค้ดตัวอย่าง
from collections import Counter
def solve(nums):
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
freq = Counter(nums)
return freq[target] > 0
print(solve([3, 2, 10, 4, 1])) # True
อินพุต / เอาต์พุต
Input: [3,2,10,4,1] Output: True