📌  相关文章
📜  最大化所选数组元素的总和,其值最多为 M

📅  最后修改于: 2022-05-13 01:56:07.580000             🧑  作者: Mango

最大化所选数组元素的总和,其值最多为 M

给定一个包含N个正数的数组arr[]和一个整数M 。任务是在arr[i] ≤ M时通过添加数组元素来最大化M的值。

注意:任何数组元素最多可以添加一次。

例子:

方法:解决方案是基于排序的概念。请按照以下步骤操作:

  • 首先,按升序对数组进行排序。
  • 对于从0 到 N-1的每个索引i ,请执行以下操作:
    • 如果M ≥ arr[i] ,则将arr[i]M相加。
    • 如果M< arr[i] ,停止迭代。
  • 返回 M 的最终值作为答案。

下面是上述方法的实现。

C++
// C++ code to implement the approach
#include 
using namespace std;
 
// Function to calculate
// the maximum value of M
// that can be obtained
int IsArrayHungry(int M, vector& arr)
{
    // Sort the array in increasing order.
    sort(arr.begin(), arr.end());
    long long sum = M;
    int N = arr.size();
 
    for (int i = 0; i < N; i++) {
        if (sum >= arr[i])
            sum += arr[i];
        else
            break;
    }
    return sum;
}
 
// Driver code
int main()
{
    vector arr{ 3, 9, 19, 5, 21 };
    int M = 10;
    int res = IsArrayHungry(M, arr);
    cout << res;
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
 
  // Function to calculate
  // the maximum value of M
  // that can be obtained
  static int IsArrayHungry(int M, int arr[ ])
  {
 
    // Sort the array in increasing order.
    Arrays.sort(arr);
    int sum = M;
    int N = arr.length;
 
    for (int i = 0; i < N; i++) {
      if (sum >= arr[i])
        sum += arr[i];
      else
        break;
    }
    return sum;
  }
 
  // Driver code
  public static void main (String[] args)
  {
    int arr[ ] = { 3, 9, 19, 5, 21 };
    int M = 10;
    int res = IsArrayHungry(M, arr);
    System.out.print(res);
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3
# Python 3 code to implement the approach
 
# Function to calculate
# the maximum value of M
# that can be obtained
def IsArrayHungry(M,  arr):
 
    # Sort the array in increasing order.
    arr.sort()
    sum = M
    N = len(arr)
 
    for i in range(N):
        if (sum >= arr[i]):
            sum += arr[i]
 
        else:
            break
 
    return sum
 
# Driver code
if __name__ == "__main__":
 
    arr = [3, 9, 19, 5, 21]
    M = 10
    res = IsArrayHungry(M, arr)
    print(res)
 
    # This code is contributed by ukasp.


C#
// C# code to implement above approach
using System;
class GFG
{
 
  // Function to calculate
  // the maximum value of M
  // that can be obtained
  static int IsArrayHungry(int M, int []arr)
  {
 
    // Sort the array in increasing order.
    Array.Sort(arr);
    int sum = M;
    int N = arr.Length;
 
    for (int i = 0; i < N; i++) {
      if (sum >= arr[i])
        sum += arr[i];
      else
        break;
    }
    return sum;
  }
 
  // Driver Code:
  public static void Main()
  {
    int []arr = { 3, 9, 19, 5, 21 };
    int M = 10;
    int res = IsArrayHungry(M, arr);
    Console.WriteLine(res);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
67

时间复杂度: O(N * logN)
辅助空间: O(1)