fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. // Fast I/O Macro
  7. void Mbappe() {
  8. ios_base::sync_with_stdio(false);
  9. cin.tie(NULL);
  10. cout.tie(NULL);
  11. }
  12.  
  13. void solve() {
  14. int n;
  15. long long d;
  16. if (!(cin >> n >> d)) return;
  17.  
  18. vector<long long> a(n);
  19. for (int i = 0; i < n; i++) {
  20. cin >> a[i];
  21. }
  22.  
  23. // Function to check if we can achieve a final height of 'mid'
  24. auto check = [&](long long mid) {
  25. long long req = mid;
  26. // Moving backwards
  27. for (int i = n - 1; i >= 0; i--) {
  28. if (req >= a[i]) {
  29. req += a[i];
  30. }
  31. }
  32. return req <= d; // Can we do this within our budget?
  33. };
  34.  
  35. long long low = 0, high = d, ans = 0;
  36.  
  37. // Binary Search on the final height
  38. while (low <= high) {
  39. long long mid = low + (high - low) / 2;
  40. if (check(mid)) {
  41. ans = mid; // If valid, save it and try for a higher height
  42. low = mid + 1;
  43. } else {
  44. high = mid - 1; // If not valid, we need to aim lower
  45. }
  46. }
  47.  
  48. cout << ans << "\n";
  49. }
  50.  
  51. int main() {
  52. Mbappe();
  53. // Vamoooos__ACCPTED
  54. int t = 1;
  55. // cin >> t; // Uncomment if the problem adds multiple test cases later
  56. while (t--) {
  57. solve();
  58. }
  59. return 0;
  60. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Standard output is empty