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

โปรแกรมหา Wealth ของลูกค้าที่ร่ำรวยที่สุด (Python)

โจทย์

มี Matrix accounts ขนาด m×n ที่ accounts[i][j] = เงินของลูกค้า i ในธนาคาร j หา Wealth (ผลรวมแถว) สูงสุด

ตัวอย่าง: Matrix 4×3 → ลูกค้าที่ 2 มี 30+5+20 = 55 (มากที่สุด)

อัลกอริธึม

  1. วนแต่ละแถว คำนวณ Sum
  2. ติดตาม Max

โค้ด Python


def solve(accounts):
    max_balance = 0
    for i in range(len(accounts)):
        ind_value = sum(accounts[i])
        if ind_value > max_balance:
            max_balance = ind_value
    return max_balance

accounts = [[10,20,15], [30,5,20], [10,5,12], [15,12,3]]
print(solve(accounts))  # Output: 55

Input / Output

Input:  [[10,20,15], [30,5,20], [10,5,12], [15,12,3]]
Output: 55