Maximize sum of values in total K steps starting at position M - GeeksforGeeks

17 Jan, 2022
Given a sorted array arr[] containing N pairs [A, B], wherer A is the position in X axis and B is the value on that position. All the positions are distinct. The array is sorted in increasing order of position. Given two integers M and K. The task is to maximize the sum of values that can be visited starting from the position M and taking total K steps where:
One can move to right or left by 1 position (from x to x+1 or x-1) by taking 1 step.
The value of any position can be added to the final sum only once.
There is no movement along the Y axis.
Examples:
Input: arr[][] = {{2, 8}, {6, 3}, {8, 6}}, M = 5, K = 4Output: 9Explanation:  The optimal way is to:Move right to position 6 and add 3. Movement 1 position. Move right to position 8 and add 6. Movement 2 position.Total movement 3 steps and sum = 3 + 6 = 9.
Input: arr[][] = {{1, 7}, {3, 6}, {4, 5}, {6, 5}}, M = 3, K = 4Output: 18Explanation: The optimal way of movement is:Add value at position 3 to answer.Move right to position 4 and add 5.Move left to position 1 and add 7.Total sum = 6 + 5 + 7 = 18.Notice that position 3 can be visited twice but value is added only once.
Input: arr[][] = {{0, 3}, {6, 4}, {8, 5}}, M = 3, K = 2Output: 0Explanation: Movement can be most K = 2 positions and cannot reach any position with points .
Approach: The approach is based on the concept of prefix sum. The range which can be covered standing at any position that needs to be determined at then the total points can be calculated from prefix sum array. Follow the steps below:
Find the Prefix Sum for the maximum possible position. After that, perform two loops.
The first loop will be when travelling to the right first and then to the left is considered.
The second loop will occur when moving to the left first, then to the right is considered.
The maximum number of Seeds covered in all feasible ranges is the final answer.
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Function to calculate maximum points// that can be collectedint maxTotalPoints(vector<vector<int> >& arr,                   int M, int K){    int MX = 2e5 + 2;    int i, l, r, ans = 0;         // Incremented positions by one    // to make calculations easier.    M++;    vector<int> prefix_sum(MX);    for (auto& it : arr)        prefix_sum[it[0] + 1] = it[1];    for (i = 1; i < MX; i++)        prefix_sum[i] += prefix_sum[i - 1];     for (r = M; r < MX && r <= M + K; r++) {        l = min(M, M - (K - 2 * (r - M)));        l = max(1, l);        ans = max(ans, prefix_sum[r] -                  prefix_sum[l - 1]);    }     for (l = M; l > 0 && l >= M - K; l--) {        r = max(M, M + (K - 2 * (M - l)));        r = min(MX - 1, r);        ans = max(ans, prefix_sum[r] -                  prefix_sum[l - 1]);    }    return ans;} // Driver codeint main(){    vector<vector<int>> arr{{2, 8}, {6, 3}, {8, 6}};    int M = 5;    int K = 4;    cout<<maxTotalPoints(arr, M, K);    return 0;}
// Java code to implement above approachimport java.util.*;class GFG{   // Function to calculate maximum points  // that can be collected  static int maxTotalPoints(int[][] arr,                            int M, int K)  {    int MX = (int) (2e5 + 2);    int i, l, r, ans = 0;     // Incremented positions by one    // to make calculations easier.    M++;    int []prefix_sum = new int[MX];    for (int []it : arr)      prefix_sum[it[0] + 1] = it[1];    for (i = 1; i < MX; i++)      prefix_sum[i] += prefix_sum[i - 1];     for (r = M; r < MX && r <= M + K; r++) {      l = Math.min(M, M - (K - 2 * (r - M)));      l = Math.max(1, l);      ans = Math.max(ans, prefix_sum[r] -                     prefix_sum[l - 1]);    }     for (l = M; l > 0 && l >= M - K; l--) {      r = Math.max(M, M + (K - 2 * (M - l)));      r = Math.min(MX - 1, r);      ans = Math.max(ans, prefix_sum[r] -                     prefix_sum[l - 1]);    }    return ans;  }   // Driver code  public static void main(String[] args)  {    int [][]arr = {{2, 8}, {6, 3}, {8, 6}};    int M = 5;    int K = 4;    System.out.print(maxTotalPoints(arr, M, K));  }} // This code is contributed by 29AjayKumar
# Python code to implement above approach # Function to calculate maximum points# that can be collecteddef maxTotalPoints(arr, M, K):    MX = (int)(2e5 + 2);    i, l, r, ans = 0, 0, 0, 0;     # Incremented positions by one    # to make calculations easier.    M += 1;    prefix_sum = [0 for i in range(MX)];    for it in arr:        prefix_sum[it[0] + 1] = it[1];    for i in range(MX):        prefix_sum[i] += prefix_sum[i - 1];     for r in range(M, (M + K + 1) and ( r < MX and r <= M + K)):        l = min(M, M - (K - 2 * (r - M)));        l = max(1, l);        ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]);     for l in range(M, (M - K - 1) and l > 0, -1):        r = max(M, M + (K - 2 * (M - l)));        r = min(MX - 1, r);        ans = max(ans, prefix_sum[r] - prefix_sum[l - 1]);     return ans; # Driver codeif __name__ == '__main__':    arr = [[2, 8], [6, 3], [8, 6]];    M = 5;    K = 4;    print(maxTotalPoints(arr, M, K));     # This code is contributed by 29AjayKumar
// C# code to implement above approachusing System;class GFG{   // Function to calculate maximum points  // that can be collected  static int maxTotalPoints(int[,] arr,                            int M, int K)  {    int MX = (int) (2e5 + 2);    int i, l, r, ans = 0;     // Incremented positions by one    // to make calculations easier.    M++;    int []prefix_sum = new int[MX];         for (int it = 0; it < arr.GetLength(0); it++) {        prefix_sum[arr[it, 0] + 1] = arr[it, 1];    }         for (i = 1; i < MX; i++)      prefix_sum[i] += prefix_sum[i - 1];     for (r = M; r < MX && r <= M + K; r++) {      l = Math.Min(M, M - (K - 2 * (r - M)));      l = Math.Max(1, l);      ans = Math.Max(ans, prefix_sum[r] -                     prefix_sum[l - 1]);    }     for (l = M; l > 0 && l >= M - K; l--) {      r = Math.Max(M, M + (K - 2 * (M - l)));      r = Math.Min(MX - 1, r);      ans = Math.Max(ans, prefix_sum[r] -                     prefix_sum[l - 1]);    }    return ans;  }   // Driver code  public static void Main()  {    int [,]arr = {{2, 8}, {6, 3}, {8, 6}};    int M = 5;    int K = 4;    Console.Write(maxTotalPoints(arr, M, K));  }} // This code is contributed by Samim Hossain Mondal.
<script>       // JavaScript code for the above approach        // Function to calculate maximum points       // that can be collected       function maxTotalPoints(arr, M, K)       {           let MX = 2e5 + 2;           let i, l, r, ans = 0;            // Incremented positions by one           // to make calculations easier.           M++;           let prefix_sum = new Array(MX).fill(0);           for (let it of arr)               prefix_sum[it[0] + 1] = it[1];           for (i = 1; i < MX; i++)               prefix_sum[i] += prefix_sum[i - 1];            for (r = M; r < MX && r <= M + K; r++) {               l = Math.min(M, M - (K - 2 * (r - M)));               l = Math.max(1, l);               ans = Math.max(ans, prefix_sum[r] -                   prefix_sum[l - 1]);           }            for (l = M; l > 0 && l >= M - K; l--) {               r = Math.max(M, M + (K - 2 * (M - l)));               r = Math.min(MX - 1, r);               ans = Math.max(ans, prefix_sum[r] -                   prefix_sum[l - 1]);           }           return ans;       }        // Driver code       let arr = [[2, 8], [6, 3], [8, 6]];       let M = 5;       let K = 4;       document.write(maxTotalPoints(arr, M, K));  // This code is contributed by Potta Lokesh   </script>
  
9
 
Time Complexity: O(X), where X is the maximum positionAuxiliary Space: O(X)
 
lokeshpotta20
29AjayKumar
samim2000
Algo-Geek 2021
prefix-sum
Algo Geek
Arrays
Greedy
Mathematical
prefix-sum
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Count of Palindrome Strings in given Array of strings
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation