From subarray problems to Kadane and applications
algorithm
Let’s start with a problem (src: leetcode#53)
Given an integer array nums, find the subarray with the largest sum, and return its sum. Constraints: ・ 1 <= nums.length <= 1e5 ・ -1e4 <= nums[i] <= 1e4 Since subarray means to a contiguous non-empty sequence of elements within an array. It’s easy to find the trivial solution where we try to calculate all possible subarray.
class Solution { public: int maxSubArray(vector<int>& nums) { int ans = INT_MIN; for (int l = 0; l < nums.
Read more...