DuongNhi99

DAYSO (Dãy con liên tiếp có tổng lớn nhất)

Nov 15th, 2021
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5. using pi32 = pair<int, int>;
  6. using pi64 = pair<int64_t, int64_t>;
  7.  
  8. const int maxN = 1e5 + 5;
  9. const ll INF = 1e18 + 7;
  10. const int MOD = 1e9 + 7;
  11.  
  12. int n;
  13. ll a[maxN];
  14.  
  15. void findSubArrayMax() {
  16.     ll best = -INF, sum = 0;
  17.     for (int i = 1; i <= n; i++) {
  18.         sum = max(a[i], sum + a[i]);
  19.         best = max(best, sum);
  20.     }
  21.     cout << best << '\n';
  22. }
  23.  
  24. void findSubArrayMaxWithIndices() {
  25.     ll best = -INF, sum = 0;
  26.     int best_start = -1, best_end = -1, tmp = 1;
  27.     for (int i = 1; i <= n; i++) {
  28.         if (sum + a[i] < a[i]) {
  29.             tmp = i;
  30.             sum = a[i];
  31.         } else {
  32.             sum += a[i];
  33.         }
  34.  
  35.         if (best < sum) {
  36.             best = sum;
  37.             best_start = tmp;
  38.             best_end = i;
  39.         }
  40.     }
  41.     cout << best << '\n';
  42.     cout << "Start from " << best_start << " to " << best_end << '\n';
  43. }
  44.  
  45. int main() {
  46. #ifdef LOCAL
  47.     freopen("in1.txt", "r", stdin);
  48. #else
  49.     freopen("DAYSO.inp", "r", stdin);
  50.     freopen("DAYSO.out", "w", stdout);
  51. #endif
  52.     ios_base::sync_with_stdio(false);
  53.     cin.tie(nullptr);
  54.  
  55.     cin >> n;
  56.     for (int i = 1; i <= n; ++i)
  57.         cin >> a[i];
  58.  
  59.     findSubArrayMax();
  60.  
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment