Maximum Subarray
I found this one in leetcode so here is the explanation:
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
And here is what I consider somewhat smart solution in Java:
public int maxSubArray(int[] nums){if(nums.length == 1)return nums[0];if(nums.length == 0)return 0;int max = Integer.MIN_VALUE;int currentMax = 0;for(int i = 0; i < nums.length; i++){if(currentMax < 0)currentMax = nums[i];elsecurrentMax = currentMax + nums[i];max = Math.max(currentMax, max);}return max;}
And here is what can be considered "dynamic programming" solution:
public int maxSubArray(int[] nums){if(nums.length == 1)return nums[0];if(nums.length == 0)return 0;int current = nums[0];int total = current;for(int i = 1; i < nums.length; i++){current = Math.max(current + nums[i], nums[i]);total = Math.max(current, total);}return total;}
To briefly explain whats happening here; The loop adds up the total as it goes through the elements.
Taking only values that'd increase the sum into account. By doing it this way only consecutive strings of numbers that'd give the highest sum will be accounted.
Also Naive solution for this one is to find all subarrays by brute force, I am not going to include it here.