Maximum Score from Subarray Minimums GFG Problem

 Given an array arr[], with 0-based indexing, select any two indexes, i and j such that i < j. From the subarray arr[i...j], select the smallest and second smallest numbers and add them, you will get the score for that subarray. Return the maximum possible score across all the subarrays of array arr[].


Examples :


Input : arr[] = [4, 3, 1, 5, 6]

Output : 11

Explanation : Subarrays with smallest and second smallest are:- [4, 3] smallest = 3,second smallest = 4

[4, 3, 1] smallest = 1, second smallest = 3

[4, 3, 1, 5] smallest = 1, second smallest = 3

[4, 3, 1, 5, 6] smallest = 1, second smallest = 3

[3, 1] smallest = 1, second smallest = 3

[3, 1, 5] smallest = 1, second smallest = 3

[3, 1, 5, 6] smallest = 1, second smallest = 3

[1, 5] smallest = 1, second smallest = 5

[1, 5, 6] smallest = 1, second smallest = 5

[5, 6] smallest = 5, second smallest = 6

Maximum sum among all above choices is, 5 + 6 = 11.

Input : arr[] = [5, 4, 3, 1, 6] 

Output : 9

Expected Time Complexity: O(n)

Expected Auxiliary Space: O(1)


Constraints:

2 ≤ arr.size ≤ 105

1 ≤ arr[i] ≤ 106


Solution :


//{ Driver Code Starts

import java.util.*;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int t = Integer.parseInt(scanner.nextLine());


        while (t-- > 0) {

            String line = scanner.nextLine();

            String[] tokens = line.split(" ");

            List<Integer> nums = new ArrayList<>();

            for (String token : tokens) {

                nums.add(Integer.parseInt(token));

            }

            int[] arr = new int[nums.size()];

            int idx = 0;

            for (int i : nums) arr[idx++] = i;

            Solution solution = new Solution();

            System.out.println(solution.pairWithMaxSum(arr));


            System.out.println("~");

        }


        scanner.close();

    }

}


// } Driver Code Ends



// User function Template for Java


class Solution {

    // Function to find pair with maximum sum

    public int pairWithMaxSum(int arr[]) {

        // Your code goes here

        int n=arr.length;


int maxi=0;


for(int i=1;i<n;i++)

{

    maxi=Math.max(maxi,arr[i-1]+arr[i]);

}


return maxi;


    }

}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence