text: # Order of indices which is lexicographically smallest and sum of elements is <= X
  
  • Difficulty Level : Medium
  • Last Updated : 10 Aug, 2021
  
  Given an array arr[] and an integer X, the task is to find the indices such that:
  
  1. The sum of elements on the found indices is â‰¤ X
  2. The number of indices is maximum possible.
  3. The order of indices is lexicographically smallest i.e. {0, 0, 1} is lexicographically smaller than {1, 0, 0}
  
  Note that any index can be chosen more than once.
  Examples:
  
  Input: arr[] = {6, 8, 5, 4, 7}, X = 11
  Output: 0 2
  Optimal answer is [0, 2] as it is lexicographically smallest.
  sum of chosen indices A[0] + A[2] = 6 + 5 = 11 which is â‰¤ 11.
  Here, [2, 3], [2, 2] or [3, 3] also give the maximum
  number of chosen indices but they are not lexicographically smallest.
  Input: arr[] = {9, 6, 8, 5, 7, 4}, X = 35
  Output: 1 3 5 5 5 5 5 5
  
  Approach: The problem looks like a variation of dynamic programming but turns out that it can be solved by a simple greedy algorithm.
  Let the index that has the first minimum value be m. Then the maximum number of indices done is n = X / A[m]. So ans = [m, m, m, …., m], where the number of m’s is n, is the order of the maximum number of indices chosen, with total sum = n x A[m]. We are also sure that optimal answer has n values in it and not more than that.
  Now, we can obtain a lexicographically smaller order with the same number of chosen indices, if we can find an index i which is smaller than m such that we can replace an index of value A[m] by an index of value A[i] without exceeding the sum X, then we can replace the first element in ans by i, making the order lexicographically smaller. To make it as lexicographically as small as possible, we would like the index i as small as possible and, then, we would like to use it as many times as possible.
  
  For example, X = 11, A = [6, 8, 5, 4, 7].
  The minimum value is at index 3 and A[3] = 4. So n = 11 / 4 = 2 and ans = [3, 3] with total sum = 4 x 2 = 8.
  To make it lexicographically smaller, we will check the indices before 3 in order.
  The first one is 6. Since 8 – 4 + 6 = 10 < 11. We have found out a smaller order [0, 3].
  If we apply 6 again, we would get 10 – 4 + 6 = 12 > 11. So we go ahead to check the next index value 8, which is too large. So we go ahead to check 5. Since 10 – 4 + 5 = 11 <= 11, we find a smaller order [0, 2]. Since there is no room left for replacement, 11 – 11 = 0, we stop here. The final answer is [0, 2].
  
  Below is the implementation of the above approach:
  
  ## C++
  
   `// C++ implementation of the approach` `#include ` `using` `namespace` `std;`   `// Function to return the chosen indices` `vector<``int``> solve(``int` `X, vector<``int``>& A)` `{` `    ``int` `min = INT_MAX;` `    ``int` `ind = -1;`   `    ``for` `(``int` `i = 0; i < A.size(); i++) {` `        ``if` `(A[i] < min) {` `            ``min = A[i];` `            ``ind = i;` `        ``}` `    ``}`   `    ``// Maximum indices chosen` `    ``int` `maxIndChosen = X / min;`   `    ``vector<``int``> ans;`   `    ``if` `(maxIndChosen == 0) {` `        ``return` `ans;` `    ``}`   `    ``for` `(``int` `i = 0; i < maxIndChosen; i++) {` `        ``ans.push_back(ind);` `    ``}`   `    ``int` `temp = maxIndChosen;` `    ``int` `sum = maxIndChosen * A[ind];`   `    ``// Try to replace the first element in ans by i,` `    ``// making the order lexicographically smaller` `    ``for` `(``int` `i = 0; i < ind; i++) {`   `        ``// If no further replacement possible return` `        ``if` `(sum - X == 0 || temp == 0)` `            ``break``;`   `        ``// If found an index smaller than ind and sum` `        ``// not exceeding X then remove index of smallest` `        ``// value from ans and then add index i to ans` `        ``while` `((sum - A[ind] + A[i]) <= X && temp != 0) {` `            ``ans.erase(ans.begin());` `            ``ans.push_back(i);` `            ``temp--;` `            ``sum += (A[i] - A[ind]);` `        ``}` `    ``}`   `    ``sort(ans.begin(), ans.end());`   `    ``return` `ans;` `}`   `// Driver code` `int` `main()` `{` `    ``vector<``int``> A = { 5, 6, 4, 8 };` `    ``int` `X = 18;`   `    ``vector<``int``> ans = solve(X, A);`   `    ``// Print the chosen indices` `    ``for` `(``int` `i = 0; i < ans.size(); i++)` `        ``cout << ans[i] << ``" "``;`   `    ``return` `0;` `}`
  
  ## Java
  
   `// Java implementation of the approach` `import` `java.util.*;`   `class` `GFG ` `{`   `// Function to return the chosen indices` `static` `Vector solve(``int` `X, Vector A)` `{` `    ``int` `min = Integer.MAX_VALUE;` `    ``int` `ind = -``1``;`   `    ``for` `(``int` `i = ``0``; i < A.size(); i++) ` `    ``{` `        ``if` `(A.get(i) < min) ` `        ``{` `            ``min = A.get(i);` `            ``ind = i;` `        ``}` `    ``}`   `    ``// Maximum indices chosen` `    ``int` `maxIndChosen = X / min;`   `    ``Vector ans = ``new` `Vector<>();`   `    ``if` `(maxIndChosen == ``0``) ` `    ``{` `        ``return` `ans;` `    ``}`   `    ``for` `(``int` `i = ``0``; i < maxIndChosen; i++) ` `    ``{` `        ``ans.add(ind);` `    ``}`   `    ``int` `temp = maxIndChosen;` `    ``int` `sum = maxIndChosen * A.get(ind);`   `    ``// Try to replace the first element in ans by i,` `    ``// making the order lexicographically smaller` `    ``for` `(``int` `i = ``0``; i < ind; i++) {`   `        ``// If no further replacement possible return` `        ``if` `(sum - X == ``0` `|| temp == ``0``)` `            ``break``;`   `        ``// If found an index smaller than ind and sum` `        ``// not exceeding X then remove index of smallest` `        ``// value from ans and then add index i to ans` `        ``while` `((sum - A.get(ind) + A.get(i)) <= X && temp != ``0``) ` `        ``{` `            ``ans.remove(``0``);` `            ``ans.add(i);` `            ``temp--;` `            ``sum += (A.get(i) - A.get(ind));` `        ``}` `    ``}`   `    ``Collections.sort(ans);`   `    ``return` `ans;` `}`   `// Driver code` `public` `static` `void` `main(String args[]) ` `{` `    ``Integer arr[] = { ``5``, ``6``, ``4``, ``8` `};` `    ``Vector A = ``new` `Vector(Arrays.asList(arr));` `    ``int` `X = ``18``;`   `    ``Vector ans = solve(X, A);`   `    ``// Print the chosen indices` `    ``for` `(``int` `i = ``0``; i < ans.size(); i++)` `        ``System.out.print(ans.get(i)+``" "``);` `}` `}`   `/* This code contributed by PrinciRaj1992 */`
  
  ## Python3
  
   `# Python3 implementation of the approach ` `import` `sys;`   `# Function to return the chosen indices ` `def` `solve(X, A) : `   `    ``minimum ``=` `sys.maxsize;` `    ``ind ``=` `-``1``;` `    `  `    ``for` `i ``in` `range``(``len``(A)) :` `        ``if` `(A[i] < minimum ) :` `            ``minimum ``=` `A[i];` `            ``ind ``=` `i;` `    `  `    ``# Maximum indices chosen ` `    ``maxIndChosen ``=` `X ``/``/` `minimum ;` `    `  `    ``ans ``=` `[];` `    `  `    ``if` `(maxIndChosen ``=``=` `0``) :` `        ``return` `ans;` `        `  `    ``for` `i ``in` `range``(maxIndChosen) :` `        ``ans.append(ind);` `        `  `    ``temp ``=` `maxIndChosen;` `    ``sum` `=` `maxIndChosen ``*` `A[ind];` `    `  `    ``# Try to replace the first element in ans by i,` `    ``# making the order lexicographically smaller` `    ``for` `i ``in` `range``(ind) :` `        `  `        ``# If no further replacement possible return ` `        ``if` `(``sum` `-` `X ``=``=` `0` `or` `temp ``=``=` `0``) :` `            ``break``;` `            `  `        ``# If found an index smaller than ind and sum ` `        ``# not exceeding X then remove index of smallest ` `        ``# value from ans and then add index i to ans` `        ``while` `((``sum` `-` `A[ind] ``+` `A[i]) <``=` `X ``and` `temp !``=` `0``) :` `            ``del``(ans[``0``]);` `            ``ans.append(i); ` `            ``temp ``-``=` `1``;` `            ``sum` `+``=` `(A[i] ``-` `A[ind]); ` `            `  `    ``ans.sort();` `    ``return` `ans; `     `# Driver code ` `if` `__name__ ``=``=` `"__main__"` `: `   `    ``A ``=` `[ ``5``, ``6``, ``4``, ``8` `]; ` `    ``X ``=` `18``; `   `    ``ans ``=` `solve(X, A); `   `    ``# Print the chosen indices ` `    ``for` `i ``in` `range``(``len``(ans)) : ` `        ``print``(ans[i],end``=` `" "``); `   `# This code is contributed by AnkitRai01`
  
  ## C#
  
   `// C# implementation of the approach` `using` `System;` `using` `System.Collections.Generic; ` `    `  `class` `GFG ` `{`   `// Function to return the chosen indices` `static` `List<``int``> solve(``int` `X, List<``int``> A)` `{` `    ``int` `min = ``int``.MaxValue;` `    ``int` `ind = -1;`   `    ``for` `(``int` `i = 0; i < A.Count; i++) ` `    ``{` `        ``if` `(A[i] < min) ` `        ``{` `            ``min = A[i];` `            ``ind = i;` `        ``}` `    ``}`   `    ``// Maximum indices chosen` `    ``int` `maxIndChosen = X / min;`   `    ``List<``int``> ans = ``new` `List<``int``>();`   `    ``if` `(maxIndChosen == 0) ` `    ``{` `        ``return` `ans;` `    ``}`   `    ``for` `(``int` `i = 0; i < maxIndChosen; i++) ` `    ``{` `        ``ans.Add(ind);` `    ``}`   `    ``int` `temp = maxIndChosen;` `    ``int` `sum = maxIndChosen * A[ind];`   `    ``// Try to replace the first element in ans by i,` `    ``// making the order lexicographically smaller` `    ``for` `(``int` `i = 0; i < ind; i++) ` `    ``{`   `        ``// If no further replacement possible return` `        ``if` `(sum - X == 0 || temp == 0)` `            ``break``;`   `        ``// If found an index smaller than ind and sum` `        ``// not exceeding X then remove index of smallest` `        ``// value from ans and then add index i to ans` `        ``while` `((sum - A[ind] + A[i]) <= X && temp != 0) ` `        ``{` `            ``ans.RemoveAt(0);` `            ``ans.Add(i);` `            ``temp--;` `            ``sum += (A[i] - A[ind]);` `        ``}` `    ``}`   `    ``ans.Sort();`   `    ``return` `ans;` `}`   `// Driver code` `public` `static` `void` `Main(String []args) ` `{` `    ``int` `[]arr = { 5, 6, 4, 8 };` `    ``List<``int``> A = ``new` `List<``int``>(arr);` `    ``int` `X = 18;`   `    ``List<``int``> ans = solve(X, A);`   `    ``// Print the chosen indices` `    ``for` `(``int` `i = 0; i < ans.Count; i++)` `        ``Console.Write(ans[i] + ``" "``);` `}` `}`   `// This code is contributed by 29AjayKumar`
  
  ## Javascript
  
   ``
  
  Output:
  
  `0 0 2 2`
  
  Time Complexity: O(NLog(N))
  
  My Personal Notes arrow_drop_up
  Recommended Articles
  Page :
metadata: {"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}