虾皮笔试|3.7 虾皮笔试题分享
13074
2022.03.07
发布于 未知归属地

3.7 虾皮笔试

T1

求最大连续子数组乘积,有正有负,复杂度要求 O(n)

class Solution:
    def GetSubArrayMaxProduct(self, nums):
        if len(nums) == 1:
            return nums[0]
        ans = max(nums)
        pre_pos = pre_neg = 0
        for i in nums:
            if i > 0:
                pre_neg = i * pre_neg
                pre_pos = max(i * pre_pos, i)
            elif i < 0:
                cur_pos = i * pre_neg
                cur_neg = min(i * pre_pos, i)
                pre_pos, pre_neg = cur_pos, cur_neg
            else:
                pre_neg = pre_pos = 0
            ans = max(ans, pre_neg, pre_pos)
        return ans

T2

计算用户逾期扣分数,连续逾期0输出0,大于0小于等于3次输出-10,大于3小于等于7输出-15,大于7输出-25

class Solution {
public:
    int calDPDScore(string dpdInfo) {
        dpdInfo += "N";
        int times = 0;
        int preCnt = 0;
        for (char c : dpdInfo) {
            if (c == 'Y') {
                ++preCnt;
            } else {
                times = max(times, preCnt);
                preCnt = 0;
            }
        }
        return 0 == times ? 0 : ((0 < times and times <= 3) ? -10 : (times <= 7 ? -15 : -25));
    }
};

T3

把 (sourceX, sourceY) -> (targetX, targetT) 的最小次数
每次操作可以把 (sourceX, sourceY) 变成 (sourceX + 1, sourceY + 1) 或者 (sourceX * 2, sourceY * 2)

class Solution {
public:
    long long GetMinCalculateCount(long long sourceX, long long sourceY, long long targetX, long long targetY) {
        // write code here
        long long times = 0;
        while (targetX > sourceX && targetY > sourceY) {
            if ((targetX & 1) == 1 && (targetY & 1) == 1) {
                targetX--;
                targetY--;
                ++times;
            } else if ((targetX & 1) == 0 && (targetY & 1) == 0) {
                targetX >>= 1;
                targetY >>= 1;
                ++times;
            } else {
                break;
            }
        }
        if (targetX > sourceX and targetY > sourceY and targetX - sourceX == targetY - sourceY) {
            times += targetY - sourceY;
            targetX = sourceX;
            targetY = sourceY;
        }
        return (targetX == sourceX && targetY == sourceY) ? times : -1;
    }
};
评论 (37)