aboutsummaryrefslogtreecommitdiff
path: root/other/max_subarray.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/max_subarray.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/max_subarray.cpp')
-rw-r--r--other/max_subarray.cpp32
1 files changed, 32 insertions, 0 deletions
diff --git a/other/max_subarray.cpp b/other/max_subarray.cpp
new file mode 100644
index 0000000..7356925
--- /dev/null
+++ b/other/max_subarray.cpp
@@ -0,0 +1,32 @@
+#include "leetcode.h"
+
+class Solution {
+public:
+ int maxSubArray(vector<int> &nums) {
+ return helper(nums, 0, nums.size() - 1);
+ }
+
+private:
+ int helper(vector<int> &nums, int l, int r) {
+ if (l > r)
+ return INT_MIN;
+ int m = l + (r - l) / 2, mL = 0, mR = 0;
+ int lMax = helper(nums, l, m - 1);
+ int rMax = helper(nums, m + 1, r);
+ for (int i = m - 1, sum = 0; i >= l; i--) {
+ sum += nums[i];
+ mL = max(sum, mL);
+ }
+ for (int i = m + 1, sum = 0; i <= r; i++) {
+ sum += nums[i];
+ mR = max(sum, mR);
+ }
+ return max(max(lMax, rMax), mL + mR + nums[m]);
+ }
+};
+
+int main() {
+ vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
+ Solution obj;
+ cout << obj.maxSubArray(nums);
+}