Given an integer array
nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.Example 1:
Input: nums = {-2,1,-3,4,-1,2,1,-5,4} Output: 6
Approach
Java
public class FindMaxSubArray {public static void main(String[] args) {int nums[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };System.out.println(maxSubArray(nums));}// function to find the maximum// subarray sumstatic int maxSubArray(int[] nums) {int max_sum = nums[0];int sum = nums[0];for (int i = 1; i < nums.length; i++) {// if sum becomes zero or negative then// make it as 0if (sum <= 0)sum = 0;// add current element into sumsum += nums[i];// update the max_summax_sum = Math.max(sum, max_sum);}// return the max sumreturn max_sum;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the maximum//subarray sumint maxSubArray(vector<int>& nums){int max_sum=nums[0];int sum=nums[0];for(int i=1;i<nums.size();i++){//if sum becomes zero or negative then//make it as 0if(sum<=0)sum=0;//add current element into sumsum+=nums[i];//update the max_summax_sum=max(sum,max_sum);}//return the max sumreturn max_sum;}int main(){vector<int> nums ={-2,1,-3,4,-1,2,1,-5,4};cout<<maxSubArray(nums);return 0;}
No comments:
Post a Comment