📌  相关文章
📜  查找给定数组的元素之和是否小于或等于 K

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

查找给定数组的元素之和是否小于或等于 K

给定一个大小为N的数组arr[]和一个整数K ,任务是找出数组元素的总和是否小于或等于 K。

例子

方法:可以通过求数组的和来解决问题,并检查得到的和是否小于或等于K。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if sum of elements
// is less than or equal to K or not
bool check(int arr[], int N, int K)
{
    // Stores the sum
    int sum = 0;
 
    for (int i = 0; i < N; i++) {
        sum += arr[i];
    }
 
    return sum <= K;
}
 
// Driver Code
int main()
{
    int arr[3] = { 1, 2, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 5;
 
    if (check(arr, N, K))
        cout << "true";
    else
        cout << "false";
    return 0;
}


Java
// Java program for the above approach
class GFG {
 
  // Function to check if sum of elements
  // is less than or equal to K or not
  static boolean check(int[] arr, int N, int K) {
 
    // Stores the sum
    int sum = 0;
 
    for (int i = 0; i < N; i++) {
      sum += arr[i];
    }
 
    return sum <= K;
  }
 
  // Driver Code
  public static void main(String args[]) {
    int[] arr = { 1, 2, 8 };
    int N = arr.length;
    int K = 5;
 
    if (check(arr, N, K))
      System.out.println("true");
    else
      System.out.println("false");
  }
}
 
// This code is contributed by Saurabh Jaiswal


Python3
# Python code for the above approach
 
# Function to check if sum of elements
# is less than or equal to K or not
def check(arr, N, K):
 
    # Stores the sum
    sum = 0;
 
    for i in range(N):
        sum += arr[i];
 
    return sum <= K;
 
# Driver Code
arr = [1, 2, 8];
N = len(arr)
K = 5
 
if (check(arr, N, K)):
    print("true");
else:
    print("false");
 
# This code is contributed by gfgking


C#
// C# program for the above approach
using System;
class GFG
{
 
  // Function to check if sum of elements
  // is less than or equal to K or not
  static bool check(int []arr, int N, int K)
  {
 
    // Stores the sum
    int sum = 0;
 
    for (int i = 0; i < N; i++) {
      sum += arr[i];
    }
 
    return sum <= K;
  }
 
  // Driver Code
  public static void Main()
  {
    int []arr = { 1, 2, 8 };
    int N = arr.Length;
    int K = 5;
 
    if (check(arr, N, K))
      Console.Write("true");
    else
      Console.Write("false");
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript



输出
false

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