【校招笔试真题】字节跳动

1-暴力贪心

题目提交链接:https://www.nowcoder.com/test/16516564/summary
题目:找出一个连续区间,得到区间最小值 * 区间和的最大值

5
2 5 7 4 3
结果:
64 = ( 5 + 7 + 4 )* 4

暴力超时,用了一步省时间的方法:
提前计算好最大最小值的情况,搜索的时候遇见最大,最小值,略过。

n = int(input())
p = []    
t = input().split(' ')
maxn = 0
for i in range(n):
    p.append(int(t[i])) 
t = list(set(p))
t.sort()
maxn = max(maxn, t[0] * sum(p))
for i in range(n):
    temp = p[i]
    l = 0
    r = n
    if(temp == t[0] or temp == t[len(t)-1]):
        continue
    for j in range(i+1, n):
        if(p[j] < temp):
            r = j
            break
    for j in range(i-1,-1,-1):
        if(p[j] < temp):
            l = j+1
            break
    maxn = max(maxn, temp * sum(p[l:r]))
print(maxn)

2-魔方旋转-dfs

题目提交链接:https://www.nowcoder.com/question/next?pid=8537068&qid=140992&tid=25216027

Nero在小魔方上做了一些改动,用数字替换每个块上面的颜色,称之为数字魔方。魔方上每一面的优美度就是这个面上4个数字的乘积,而魔方的总优美度就是6个面优美度总和。
现在Nero有一个数字魔方,他想知道这个魔方在操作不超过5次的前提下能达到的最大优美度是多少。
魔方展开后每一块的序号如下图:
【校招笔试真题】字节跳动_第1张图片

t = input()
p = []
for i in t.split(' '):        
    p.append(int(i))

'''-1表示该位置不变'''
direc = [[ 1, 3, 0, 2, 23, 22, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 8 ],
    [ 10, 4, -1, -1, 18, -1, -1, -1, -1, 0, 19, -1, -1, -1, -1, 1, -1, -1, 15, 9, 21, 23, 20, 22 ],
    [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 21, 20, 10, 11, 12, 13, 18, 16, 19, 17, 15, 14, -1, -1 ],
    [ 20, -1, 22, -1, 10, 4, 0, -1, -1, -1, 11, 5, 2, -1, -1, -1, 6, -1, 12, -1, 16, -1, 18, -1 ],
    [ -1, 21, -1, 23, -1, -1, -1, 1, 9, 15, -1, -1, -1, 3, 8, 14, -1, 7, -1, 13, -1, 17, -1, 19 ],
    [ -1, -1, 11, 5, -1, 16, 12, 6, 2, -1, -1, 17, 13, 7, 3, -1, 14, 8, -1, -1, -1, -1, -1, -1 ]]

def cal_sum(m):
    return m[0] * m[1] * m[2] * m[3] + m[4] * m[5] * m[10] * m[11] + m[6] * m[7] * m[12] * m[13] + m[8] * m[9] * m[14] * m[15] + m[16] * m[17] * m[18] * m[19] + m[20] * m[21] * m[22] * m[23]

maxn = cal_sum(p)
def dfs(v, roate_num):    
    global maxn
    global direc
    temp = cal_sum(v)
    if(temp > maxn):
        maxn = temp    
    if(roate_num == 5):
        return
    cur = [v[j] for j in range(24)]
    for i in range(6):        
        for j in range(24):
            if(direc[i][j] != -1):
                cur[j]  = v[direc[i][j]]
        roate_num += 1
        dfs(cur, roate_num)
        cur = [v[j] for j in range(24)]
        roate_num -= 1

dfs(p, 0)
print(maxn)

你可能感兴趣的:(春秋招笔试)