Leetcode 第 137 场双周赛

Powered by:NEFU AB-IN

Link

文章目录

  • [Q1. 长度为 K 的子数组的能量值 I](#Q1. 长度为 K 的子数组的能量值 I)
  • [Q2. 长度为 K 的子数组的能量值 II](#Q2. 长度为 K 的子数组的能量值 II)
  • [Q3. 放三个车的价值之和最大 I](#Q3. 放三个车的价值之和最大 I)
  • [Q4. 放三个车的价值之和最大 II](#Q4. 放三个车的价值之和最大 II)

Q1. 长度为 K 的子数组的能量值 I

题意

给你一个长度为 n 的整数数组 nums 和一个正整数 k 。

一个数组的 能量值 定义为:

如果 所有 元素都是依次 连续 且 上升 的,那么能量值为 最大 的元素。

否则为 -1 。

你需要求出 nums 中所有长度为 k 的子数组的能量值。

请你返回一个长度为 n - k + 1 的整数数组 results ,其中 results[i] 是子数组 nums[i...(i + k - 1)] 的能量值。

思路

这个数据范围小,可以直接暴力

代码

python 复制代码
# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)

# Set recursion limit
setrecursionlimit(int(2e9))


class Arr:
    array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])
    array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
    graph = staticmethod(lambda size=N: [[] for _ in range(size)])


class Math:
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)


class IO:
    input = staticmethod(lambda: stdin.readline().strip())
    read = staticmethod(lambda: map(int, IO.input().split()))
    read_list = staticmethod(lambda: list(IO.read()))
    read_mixed = staticmethod(lambda *types: [t(v) for t, v in zip(types, IO.input().split())])


class Std:
    pass

# --------------------------------------------------------------- Division line ------------------------------------------------------------------


class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        res = []

        for i in range(n - k + 1):
            flag = True
            max_ = nums[i]

            for j in range(i + 1, i + k):
                if nums[j] != nums[j - 1] + 1:
                    flag = False
                    break
                max_ = Math.max(max_, nums[j])

            if flag:
                res.append(max_)
            else:
                res.append(-1)

        return res

Q2. 长度为 K 的子数组的能量值 II

题意

给你一个长度为 n 的整数数组 nums 和一个正整数 k 。

一个数组的 能量值 定义为:

如果 所有 元素都是依次 连续 且 上升 的,那么能量值为 最大 的元素。

否则为 -1 。

你需要求出 nums 中所有长度为 k 的子数组的能量值。

请你返回一个长度为 n - k + 1 的整数数组 results ,其中 results[i] 是子数组 nums[i...(i + k - 1)] 的能量值。

思路

求前缀和即可,然后通过等差数列求和判断是否相等,而且d = 1

代码

python 复制代码
# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)

# Set recursion limit
setrecursionlimit(int(2e9))


class Arr:
    array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])
    array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
    graph = staticmethod(lambda size=N: [[] for _ in range(size)])


class Math:
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)


class IO:
    input = staticmethod(lambda: stdin.readline().strip())
    read = staticmethod(lambda: map(int, IO.input().split()))
    read_list = staticmethod(lambda: list(IO.read()))
    read_mixed = staticmethod(lambda *types: [t(v) for t, v in zip(types, IO.input().split())])


class Std:
    class PrefixSum:
        def __init__(self, nums: List[int]):
            """Initializes the PrefixSum object with the given list of numbers.

            Args:
                nums (List[int]): The input array of integers (0-based index).
            """
            self._n = len(nums)
            self._prefix_sum_ = Arr.array(0, self._n + 1)  # 1-based index

            # Compute the prefix sum with adjusted indexing
            for i in range(1, self._n + 1):
                # Adjust nums index by subtracting 1 to map 1-based prefix_sum to 0-based nums
                self._prefix_sum_[i] = self._prefix_sum_[i - 1] + nums[i - 1]

        def query(self, left: int, right: int) -> int:
            """Returns the sum of elements in the range [left, right]. The input coordinates is 0-based indexing."""
            # Convert the 0-based indices to 1-based by adding 1
            return self._prefix_sum_[right + 1] - self._prefix_sum_[left]

# --------------------------------------------------------------- Division line ------------------------------------------------------------------


class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        res = []

        pre = Std.PrefixSum(nums)
        for i in range(n - k + 1):
            flag = pre.query(i, i + k - 1) == (k * (nums[i] + nums[i + k - 1]) // 2) and nums[i + k - 1] - nums[i] == k - 1

            if flag:
                res.append(nums[i + k - 1])
            else:
                res.append(-1)

        return res

Q3. 放三个车的价值之和最大 I

Q4. 放三个车的价值之和最大 II

题意

给你一个 m x n 的二维整数数组 board ,它表示一个国际象棋棋盘,其中 board[i][j] 表示格子 (i, j) 的 价值 。

处于 同一行 或者 同一列 车会互相 攻击 。你需要在棋盘上放三个车,确保它们两两之间都 无法互相攻击 。

请你返回满足上述条件下,三个车所在格子 值 之和 最大 为多少。

思路

类似贪心,可以推出来,每一列和每一行,最多取三个最大的值,取出来全放进set中去重,然后进行三个棋子的挨个枚举即可

偏暴力,应该不是最优解法,复杂度最大为排序的复杂度,n最大为1e7左右

代码

python 复制代码
'''
Author: NEFU AB-IN
Date: 2024-08-17 22:12:44
FilePath: \LeetCode\CP137_2\c\c.py
LastEditTime: 2024-08-17 23:11:38
'''
# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)

# Set recursion limit
setrecursionlimit(int(2e9))


class Arr:
    array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])
    array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
    graph = staticmethod(lambda size=N: [[] for _ in range(size)])


class Math:
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)


class IO:
    input = staticmethod(lambda: stdin.readline().strip())
    read = staticmethod(lambda: map(int, IO.input().split()))
    read_list = staticmethod(lambda: list(IO.read()))
    read_mixed = staticmethod(lambda *types: [t(v) for t, v in zip(types, IO.input().split())])


class Std:
    pass

# --------------------------------------------------------------- Division line ------------------------------------------------------------------


class Solution:
    def maximumValueSum(self, board: List[List[int]]) -> int:
        m, n = len(board), len(board[0])
        row_dict = defaultdict(list)
        col_dict = defaultdict(list)

        for i in range(m):
            for j in range(n):
                value = board[i][j]

                if len(row_dict[i]) < 3:
                    row_dict[i].append((value, i, j))
                    row_dict[i].sort(reverse=True, key=lambda x: x[0])
                elif value > row_dict[i][-1][0]:
                    row_dict[i][-1] = (value, i, j)
                    row_dict[i].sort(reverse=True, key=lambda x: x[0])

                if len(col_dict[j]) < 3:
                    col_dict[j].append((value, i, j))
                    col_dict[j].sort(reverse=True, key=lambda x: x[0])
                elif value > col_dict[j][-1][0]:
                    col_dict[j][-1] = (value, i, j)
                    col_dict[j].sort(reverse=True, key=lambda x: x[0])

        row_max_set = set()
        for i in range(m):
            row_max_set.update(row_dict[i])
        for j in range(n):
            row_max_set.update(col_dict[j])

        row_max = list(row_max_set)
        row_max.sort(reverse=True, key=lambda x: x[0])

        res = -INF
        for i in range(len(row_max)):
            v1, r1, c1 = row_max[i]
            for j in range(i + 1, len(row_max)):
                v2, r2, c2 = row_max[j]
                if c1 == c2 or r1 == r2:
                    continue
                for k in range(j + 1, len(row_max)):
                    v3, r3, c3 = row_max[k]
                    if r2 != r3 and r1 != r3 and c2 != c3 and c1 != c3:
                        res = Math.max(res, v1 + v2 + v3)
                        break

        return res
相关推荐
树在风中摇曳6 分钟前
【牛客排序题详解】归并排序 & 快速排序深度解析(含 C 语言完整实现)
c语言·开发语言·算法
minji...9 分钟前
算法---模拟/高精度/枚举
数据结构·c++·算法·高精度·模拟·枚举
执笔论英雄1 小时前
【大模型训练】forward_backward_func返回多个micro batch 损失
开发语言·算法·batch
草莓熊Lotso2 小时前
《算法闯关指南:优选算法--模拟》--41.Z 字形变换,42.外观数列
开发语言·c++·算法
啊吧怪不啊吧2 小时前
算法王冠上的明珠——动态规划之斐波那契数列问题
大数据·算法·动态规划
无敌最俊朗@9 小时前
力扣hot100-206反转链表
算法·leetcode·链表
Kuo-Teng9 小时前
LeetCode 279: Perfect Squares
java·数据结构·算法·leetcode·职场和发展
王哈哈^_^9 小时前
YOLO11实例分割训练任务——从构建数据集到训练的完整教程
人工智能·深度学习·算法·yolo·目标检测·机器学习·计算机视觉
檐下翻书17310 小时前
从入门到精通:流程图制作学习路径规划
论文阅读·人工智能·学习·算法·流程图·论文笔记
CoderYanger10 小时前
B.双指针——3194. 最小元素和最大元素的最小平均值
java·开发语言·数据结构·算法·leetcode·职场和发展·1024程序员节