Find if sum of elements of given Array is less than or equal to K
Last Updated :
09 Feb, 2022
Given an array arr[] of size N and an integer K, the task is to find whether the sum of elements of the array is less than or equal to K or not.
Examples:
Input: arr[] = {1, 2, 8}, K = 5
Output: false
Explanation: Sum of the array is 11, which is greater than 5
Input: arr[] = {2}, K = 5
Output: true
Approach: The problem can be solved by finding the sum of the array, and, checking whether the obtained sum is less than or equal to K or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool check( int arr[], int N, int K)
{
int sum = 0;
for ( int i = 0; i < N; i++) {
sum += arr[i];
}
return sum <= K;
}
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
class GFG {
static boolean check( int [] arr, int N, int K) {
int sum = 0 ;
for ( int i = 0 ; i < N; i++) {
sum += arr[i];
}
return sum <= K;
}
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" );
}
}
|
Python3
def check(arr, N, K):
sum = 0 ;
for i in range (N):
sum + = arr[i];
return sum < = K;
arr = [ 1 , 2 , 8 ];
N = len (arr)
K = 5
if (check(arr, N, K)):
print ( "true" );
else :
print ( "false" );
|
C#
using System;
class GFG
{
static bool check( int []arr, int N, int K)
{
int sum = 0;
for ( int i = 0; i < N; i++) {
sum += arr[i];
}
return sum <= K;
}
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" );
}
}
|
Javascript
<script>
function check(arr, N, K)
{
let sum = 0;
for (let i = 0; i < N; i++) {
sum += arr[i];
}
return sum <= K;
}
let arr = [1, 2, 8];
let N = arr.length;
let K = 5;
if (check(arr, N, K))
document.write( "true" );
else
document.write( "false" );
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...