欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Leetcode3282. 到达数组末尾的最大得分

Leetcode3282. 到达数组末尾的最大得分

2025/12/14 9:31:28 来源:https://blog.csdn.net/ProgramNovice/article/details/142217627  浏览:    关键词:Leetcode3282. 到达数组末尾的最大得分

Every day a Leetcode

题目来源:3282. 到达数组末尾的最大得分

解法1:动态规划

代码:

class Solution {
public:long long findMaximumScore(vector<int>& nums) {if (nums.size() <= 1) return 0LL;int n = nums.size();vector<long long> dp(n + 1);dp[0] = 0;for (int j = 1; j <= n; j++) {for (int i = 1; i < j; i++) {dp[j] = max(dp[j], dp[i] + 1LL * (j - i) * nums[i - 1]);}}return dp[n];}
};

结果:超时

复杂度分析:

时间复杂度:O(n2),其中 n 是数组 nums 的长度。

空间复杂度:O(n),其中 n 是数组 nums 的长度。

解法2:动态规划 + 贪心

维护一个 maxIndex 表示之前 nums 元素最大值的下标,从贪心的角度思考,从maxIndex 跳到当前下标 i,增加的值最大。

代码:

/** @lc app=leetcode.cn id=3282 lang=cpp** [3282] 到达数组末尾的最大得分*/// @lc code=start
class Solution
{
public:long long findMaximumScore(vector<int> &nums){if (nums.size() <= 1)return 0LL;int n = nums.size();vector<long long> dp(n);dp[0] = 0;int maxIndex = 0;for (int i = 1; i < n; i++){dp[i] = dp[maxIndex] + 1LL * (i - maxIndex) * nums[maxIndex];if (nums[i] > nums[maxIndex])maxIndex = i;}return dp[n - 1];}
};
// @lc code=end

结果:

在这里插入图片描述

复杂度分析:

时间复杂度:O(n),其中 n 是数组 nums 的长度。

空间复杂度:O(n),其中 n 是数组 nums 的长度。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词