-1

For Example - If given array is :- int[] arr = { 1, 4, 8, 3 };

The result Subarray should be:

1 , 
1 ,4 , 
1 ,4 ,8 , 
1 ,4 ,8 ,3 ,  

4 , 
4 ,8 , 
4 ,8 ,3 ,  

8 , 
8 ,3 ,
 
3 , 

and than , Maximum of each subarray are :- 1 ,4 ,8,8,4,8,8,8,8,3 therefore sum of all maximum should be :- 1 + 4 +8+8+4+8+8+8+8=3 = 60

To Write Subarray, I was able to do this with loop:-

{
            for(int j = i ; j <= n ; j++)
            {
                for(int k = i ; k < j ; k++)
                {
                    Console.Write(arr[k] + " ," );                
                    
                }
                
        Console.WriteLine(" " );
            }
        }
        
    }

After this, I was trying to store maximum values in the Dictionary data structure but was not able to find where exactly use dictionary structure and how to use Math.max statement.

IDictionary<int, int> maxValue = new Dictionary<int, int>();
4
  • You don't really need any of that. You can keep track of the max for the sub array, you are going through it to print it anyway. Then after iterating it just add max to total. Commented Feb 7, 2022 at 18:56
  • 1
    Refer this one: stackoverflow.com/questions/55780200/… for an O(n) solution using monotonic stacks (instead of maximums, it calculates the minimums). Your current approach would likely TLE. Commented Feb 7, 2022 at 19:19
  • @maraca How? Can you show me? Commented Feb 7, 2022 at 19:26
  • See also this question, which solves the case for maximums and minimums too, with a variety of methods. Commented Feb 7, 2022 at 20:29

1 Answer 1

1

If you would only need the sum, then it could be solved in O(n). Because you need to print the sub-arrays this is not possible. But it also makes it pretty easy (I don't know C#, replace the print with what you need):

int total = 0;
for (int start = 0; start < n; start++) {
    for (int end = start + 1; end <= n; end++) {
        int max = arr[start];
        print(arr[start]);
        for (int i = start + 1; i < end; i++) {
            print(", " + arr[i]);
            if (arr[i] > max)
                max = arr[i];
        }
        total += max;
        print("\n");
    }
    print("\n");
}
print(total); // or whatever you want to do with it

This avoids the last comma, but you can switch it back if you want to. Also readable variable names can be helpful.

end is not inclusive, I prefer it that way because then you could get the length of the sub-array with end - start. E.g. Java's substring works exactly the same.

Sign up to request clarification or add additional context in comments.

1 Comment

printing subarray is only for representational purposes, If you have a better-optimized solution please do also post for others.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.