[英]How do I reduce Time Complexity of this solution in C++?
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
给定一个 integer 数组 nums,找到总和最大的连续子数组(至少包含一个数)并返回其总和。
Example:例子:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.输入:[-2,1,-3,4,-1,2,1,-5,4], Output: 6 解释:[4,-1,2,1] 的最大和 = 6。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max=INT_MIN;
int result;
int i,j;
if(nums.size()==1)
return nums[0];
if(nums.size()==0)
return 0;
for(i=0;i<nums.size();i++)
{
for(j=i;j<nums.size();j++)
{
result=accumulate(nums.begin()+i,nums.begin()+j+1,0);
if(result>max)
max=result;
}
}
return max;
}
};
It has passed 200/202 test cases but got time limit extended issue on the rest 2 testcases.How do I optimize this?
它已经通过了 200/202 个测试用例,但是在 rest 2 个测试用例上出现了时间限制延长问题。我该如何优化呢?
This can be done using Kadane's Algorithm .这可以使用Kadane 的算法来完成。
#include<algorithm> //this header file is required for max function.
class Solution
{
public:
int maxSubArray(vector<int>& nums) {
int temp=0;
int max_sum=0;
for(int i=0;i<nums.size();i++)
{
temp=max(temp+nums[i],nums[i]);
max_sum=max(temp,max_sum);
}
return max_sum;
}
};
Below this is achieved in only one loop, from one the first googled results .下面这仅在一个循环中实现,从 第一个谷歌搜索结果开始。 With a little bookkeeping you can also hold the first and last element positions of the largest subsequence with sum
max_so_far
.通过一点簿记,您还可以使用 sum
max_so_far
最大子序列的第一个和最后一个元素位置。
#include<iostream>
#include<climits>
using namespace std;
int maxSubArraySum(int a[], int size)
{
int max_so_far = INT_MIN, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
Have look at this link: https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/看看这个链接: https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
Couple of efficient solutions there.那里有几个有效的解决方案。
Main idea is to keep a maxSum variable, that will keep track of maximum sum seen so far.主要思想是保留一个 maxSum 变量,它将跟踪迄今为止看到的最大总和。 You also need a currentSum variable that keeps track of sum in current window.
您还需要一个 currentSum 变量来跟踪当前 window 中的总和。 Everytime you add a positive number to current sum,compare it to maxSum and update maxSum if currentSum > maxSum.
每次向当前总和添加一个正数时,将其与 maxSum 进行比较,如果 currentSum > maxSum 则更新 maxSum。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.