当你的才华不能撑起你的野心时,就是你该选择学习的时候了!

算法面试题:一

面试题:写算法,实现数组中找到2个点分割数组,使得三部分数组元素的和相等的方法,备注:求和不包括这两个点

Python实现:

def find_tripartition(arr):
    total_sum = sum(arr)
    if total_sum % 3 != 0:
        return "No solution, as the sum of elements cannot be divided by 3 evenly."
    target_sum = total_sum // 3
    n = len(arr)
    for i in range(n - 2):
        left_sum = sum(arr[:i+1])
        if left_sum > target_sum:
            continue
        for j in range(i + 1, n - 1):
            mid_sum = sum(arr[i+1:j+1])
            if mid_sum > target_sum:
                continue
            right_sum = total_sum - left_sum - mid_sum
            if right_sum == target_sum:
                return (i, j)
    return "No valid tripartition found."

#arr = [1, 2, 0, 0, 3, 0, 2, 1]
[3, 0, 3, 0, 3, 0, 0, 3]

print(find_tripartition(arr))

 

posted @ 2024-09-07 23:54  hofmann  阅读(7)  评论(0编辑  收藏  举报