Java / Programs
Write a Java program to find the subArray in an Integer Array that has maximum Sum of the elements.
public class FindSubArrayWithMaxSum { public static void main(String[] args) { // Creating a bucket of integer array with various test values for unit testing int[][] myArr = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, -11 }, { 1, 2, 3, 0, 4, 3, -1, 3, 5, 5, 6, 6, -2, 50 }, { -3, 0, -1 }, { 0, -1 }, {}, { -2 }, { 2 }, { 0 }, { 1, 2, 3, -1, 1, 2, 3, 4, 0, -1, 1, 1 } }; // For each of the above data set find the sumArray with Maximum sum IntStream.range(0, myArr.length).mapToObj(i -> myArr[i]).parallel() .forEach(FindSubArrayWithMaxSum::findMaxSumSubArray); } static void findMaxSumSubArray(int[] myArr) { if (myArr.length == 0) return; int positionI = 0, positionJ = 0; int tempPositionI = 0, tempPositionJ = 0; int maxSum, tempSum; maxSum = tempSum = myArr[0]; for (int i = 1; i < myArr.length; i++) { if (tempPositionI >= i || tempSum < 0) { tempPositionI = tempPositionJ = i; tempSum = myArr[i]; continue; } if ((tempSum + myArr[i]) >= tempSum) { tempSum += myArr[i]; tempPositionJ = i; } else if (i + 1 < myArr.length) { positionI = tempPositionI; positionJ = tempPositionJ; maxSum = tempSum; tempPositionI = i + 1; } } if (tempSum > maxSum) { positionI = tempPositionI; positionJ = tempPositionJ; maxSum = tempSum; } System.out.println( Arrays.toString(myArr) + " >> Start Position: " + positionI + " End Position: " + positionJ + ", Sum: " + maxSum); } }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
