-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay15.cpp
113 lines (54 loc) · 1.34 KB
/
Day15.cpp
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define bug cout <<"-----------------"<<endl
// problem name - Maximum Sum Circular Subarray
// tutorial link from where i have learnt this : https://www.youtube.com/watch?v=C4G8m3vvWFA
class Solution {
public:
int go(vector<int>& Array) {
int n = Array.size();
int Curr_Sum = Array[0];
int Max_Sum = Array[0];
int Right = 0;
for (int i = 1; i <= n - 1; i++)
{
Curr_Sum = max(Array[i], Curr_Sum + Array[i]);
if (Curr_Sum > Max_Sum)
{
Max_Sum = Curr_Sum;
Right = i;
}
}
int Sum = 0;
int Left;
for (int i = Right; i >= 0; i--)
{
Sum += Array[i];
if (Sum == Max_Sum)
{
Left = i;
break;
}
}
return Max_Sum;
}
int maxSubarraySumCircular(vector<int>& Arr) {
int ans1 = this->go(Arr);
int tot = 0;
for (auto it : Arr)tot += it;
for (int i = 0; i < Arr.size(); i++) Arr[i] = Arr[i] * (-1);
int ans2 = this->go(Arr);
ans2 *= -1;
if (tot - ans2 != 0) ///special case
return max(ans1, tot - ans2);
else
return ans1;
}
};;
int main() {
Solution ob;
vector <int> a = { -2,-3,-1 };
cout <<ob.maxSubarraySumCircular(a);
return 0;
}