#include<iostream> using namespace std; long long dp[500100][2]; long long t[500100]; const long long niedoszlam=-1000000000000000000; int main() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); long long n,suma=0,k,j_max=0; cin>>n; for(int i=1;i<=n;i++) { cin>>t[i]; suma+=t[i]; } if(suma<0) cout<<"-1"; else{ for(int i=1;i<=n;i++) { dp[i][0]=niedoszlam; dp[i][1]=niedoszlam; } for(int i=1;i<=n;i++) { for(int j=i-1;j>=0;j--) { if(dp[j][i%2]==niedoszlam) continue; if(dp[j][i%2]+t[i]>=0 && i<n) dp[j+1][(i+1)%2]=max((long long)0,dp[j+1][(i+1)%2]); dp[j][(i+1)%2]=dp[j][i%2]+t[i]; } } for(int j=n-1;j>=0;j--) { if(dp[j][(n+1)%2]<0) continue; else{ cout<<n-1-j; break; } } } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #include<iostream> using namespace std; long long dp[500100][2]; long long t[500100]; const long long niedoszlam=-1000000000000000000; int main() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); long long n,suma=0,k,j_max=0; cin>>n; for(int i=1;i<=n;i++) { cin>>t[i]; suma+=t[i]; } if(suma<0) cout<<"-1"; else{ for(int i=1;i<=n;i++) { dp[i][0]=niedoszlam; dp[i][1]=niedoszlam; } for(int i=1;i<=n;i++) { for(int j=i-1;j>=0;j--) { if(dp[j][i%2]==niedoszlam) continue; if(dp[j][i%2]+t[i]>=0 && i<n) dp[j+1][(i+1)%2]=max((long long)0,dp[j+1][(i+1)%2]); dp[j][(i+1)%2]=dp[j][i%2]+t[i]; } } for(int j=n-1;j>=0;j--) { if(dp[j][(n+1)%2]<0) continue; else{ cout<<n-1-j; break; } } } return 0; } |