Thread: Given an integer array. Find the LONGEST subarray with the HIGHEST sum.

  1. #1
    Banned
    Join Date
    Oct 2022
    Posts
    7

    Given an integer array. Find the LONGEST subarray with the HIGHEST sum.

    Hello, I am studying for an interview coding exam and came across this question. I attempted it in C#; here is my embarrassing response; I'm not sure if it's correct, but I'm guessing not; could someone maybe kindly share the answer so that when I rework on the solution, I can at least have the answer to validate the output? Thanks.
    Sample data:
    Code:
    int[] arr = {5, 1, -7, 3, 7};
    My code:
    Code:
    int[] LargestsubarrayMaxSum(int[] arr){
        int temp = 0;
        int[] resultArr = new int[arr.Length];
    
        for (int i = 0; i < arr.Length - 1; i++)
        {
            if (i != 0)
            {
                foreach (int item in resultArr)
                {
                    temp += item;
                }
    
                if (temp + arr[i + 1] > 0)
                {
                    resultArr[i + 1] = temp + arr[i + 1];
                }
            }
            else
            {
                if ((arr[i] + arr[i + 1]) >= 0)
                {
                    resultArr[i] = arr[i];
                    resultArr[i + 1] = arr[i] + arr[i + 1];
                }
                else
                {
                    resultArr[i] = arr[i];
                    resultArr[i + 1] = 0;
                }
            }
        }
        return resultArr; }
    According to this <<rubbish url>>, I could either apply Enigmativity's solution or add the additional order by using subseq.Count() descending.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,664
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to find the longest meaning substring?
    By shaoshao in forum C Programming
    Replies: 7
    Last Post: 06-03-2011, 12:15 PM
  2. Find last largest integer in array?
    By schmidtc in forum C Programming
    Replies: 2
    Last Post: 07-05-2010, 01:00 PM
  3. Find a certain bits in an integer array?
    By zyphirr in forum C Programming
    Replies: 1
    Last Post: 11-02-2008, 03:27 PM
  4. Replies: 4
    Last Post: 01-05-2008, 11:30 PM

Tags for this Thread