![](/img/trans.png)
[英]maximum sum subarray of window k algorithm not returning correctly for start index
[英]algorithm:Finding the first k1,k2,k3 th maximum subarray sum
大家晚上晚點,直奔問題。
我們得到一個整數數組。我們必須報告第k1,k2和k3個最大子數組和。數組大小(最大10 ^ 6)。元素都是+ ve和-ve。 K1,K2,K3 <= 2200;
換句話說,我們必須找到S [K]的值,其中to數組S包含所有可能的連續子數組的和(以降序排列)。
線性解可能是O(n)還是O(nlogn)?
我的方法是這樣的(不正確)
我內心的某個地方知道可以通過對數組進行排序並使用兩個指針技術來解決這一問題,我可以找到所有可能的子數組和。對中間和進行排序后,我們可以解決,但我無法正確實現。
有人有其他方法或相同方法但正確嗎?
如果您想看到我對問題的執行
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define nline cout<<"\n"
#define fast ios_base::sync_with_stdio(false)cin.tie(0)
#define ain(A, B, C) assert(IN(A, B, C))
#define ull unsigned long long int
#define ll long long int
#define pii pair<int,int>
#define MAXX 100009
#define fr(a,b,i) for(int i=a;i<b;i++)
vector<int>G[MAXX];
bool vis[MAXX];
int n,k1,k2,k3;
bool cmp(const int &l,const int &r){
return l>r;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>k1>>k2>>k3;
--k1,--k2,--k3;
int a[n+1];
for(int i=0;i<n;i++)cin>>a[i];
sort(a,a+n);
int l=0,e=n-1;
vector<ll>v;
int sum=0;
while(e>=l)
{
if(a[e]>a[l])
{
sum+=a[e];
v.pb(sum);
e--;
}
else
{
sum+=a[l];
v.pb(sum);
l++;
}
}
sort(v.begin(),v.end(),cmp);
cout<<v[k1]<<" "<<v[k2]<<" "<<v[k3]<<endl;
}
return 0;
}
根據Wikipedia的介紹 ,您應該能夠使用Kadane算法在O(n)中找到1個子數組,所以我的猜測是找到最大子數組,將其存儲,然后將其刪除,然后再次搜索第二個最大子數組,依此類推。 ..
我假設之后,您使用的是Kadane算法的版本,該版本可跟蹤子數組的索引。
偽碼
init_array(array) //here you initialize your array with the number you want in it
start1,end1,sum1 = kadane(array) // you find the starting index, the ending index and the maximal sum of the subarray
remove(array, start1,end1) // here you remove the subarray in array.
如果執行3次,則您擁有3個最大子數組,可以對其求和。
我看到的唯一限制是,您需要刪除O(n)或更小的子數組,以使算法保持O(n)。 (代替刪除它,您可以跟蹤可以訪問或無法訪問的wich索引,wich可能會更快)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.