Skip to content

Commit

Permalink
max subarray
Browse files Browse the repository at this point in the history
  • Loading branch information
sachuverma committed Nov 2, 2020
1 parent dc16745 commit 8dcf102
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 3 deletions.
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"valarray": "cpp",
"bitset": "cpp",
"chrono": "cpp",
"algorithm": "cpp"
"algorithm": "cpp",
"limits": "cpp"
}
}
57 changes: 57 additions & 0 deletions Leetcode-Top-Interview-Questions/Maximum Subarray.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
Maximum Subarray
===============
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [0]
Output: 0
Example 4:
Input: nums = [-1]
Output: -1
Example 5:
Input: nums = [-2147483647]
Output: -2147483647
Constraints:
1 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
*/

class Solution
{
public:
int maxSubArray(vector<int> &nums)
{
int n = nums.size();
if (n == 0)
return 0;

vector<int> dp(n, 0);
dp[0] = nums[0];
int ans = nums[0];

for (int i = 1; i < n; ++i)
{
dp[i] = max(nums[i], nums[i] + dp[i - 1]);
ans = max(ans, dp[i]);
}
return ans;
}
};
4 changes: 2 additions & 2 deletions Leetcode-Top-Interview-Questions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@
### 6. Dynamic Programming

- [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) - [Cpp Solution](./Climbing%20Stairs.cpp)
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) - [Cpp Solution](./.cpp)
- [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) - [Cpp Solution](./.cpp)
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) - [Cpp Solution](./Best%20Time%20to%20Buy%20and%20Sell%20Stock.cpp)
- [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) - [Cpp Solution](./Maximum%20Subarray.cpp)
- [House Robber](https://leetcode.com/problems/house-robber/) - [Cpp Solution](./.cpp)

### 7. Design
Expand Down

0 comments on commit 8dcf102

Please sign in to comment.