classSolution{public:intmaxSubArray(vector<int>&nums){// We need a variable to store the maximum sum found so far// We start it at the smallest possible integer value so that any real sum// from the array will be larger than itintmaxSum=INT_MIN;// 'i' will go from the first element to the last elementfor(inti=0;i<nums.size();i++){// Reset the sum for each new subarrayintcurrentSum=0;// 'i' will go from the first element to the last element.for(intj=i;j<nums.size();j++){currentSum+=nums[j];// Our running sum// If the current one is bigger, we update maxSummaxSum=max(maxSum,currentSum);}}returnmaxSum;}};
classSolution{public:intmaxSubArray(vector<int>&nums){// Initialize 'maxSum' to the smallest possible integer,// so any number in the array will be larger and update maxSum correctlyintmaxSum=INT_MIN;// 'currentSum' holds the sum of the current subarray we're exploring// It starts at zero because we haven't added any numbers yetintcurrentSum=0;// Iterate over each number oncefor(intnum:nums){// Add the current number to 'currentSum' extend the current subarraycurrentSum+=num;// Update 'maxSum' if the current sum is better than what we had beforemaxSum=max(maxSum,currentSum);// If the current sum dips below zero, reset it to zero.// This means the current subarray is hurting the total sum,// so start fresh from the next element.if(currentSum<0){currentSum=0;}}returnmaxSum;}};
Warning
LINK
You are about to visit a link which has been flagged with the above content warnings. Do you wish to continue?