📜  求和在 [(K+1)/2, K] 范围内的子序列

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

求和在 [(K+1)/2, K] 范围内的子序列

给定一个由N个正整数和一个正整数K组成的数组arr[] ,任务是找到一个数组arr[]的子序列,其元素之和在[(K+1)/2, K]范围内.如果有子序列,则打印子序列的索引,否则打印-1

注意:这个问题可能有多个答案,打印其中任何一个。

例子:

方法:这个问题可以通过遍历数组arr[ ]来解决。请按照以下步骤解决此问题:

  • 初始化一个向量ans来存储结果子序列的索引和totalSum来存储元素的总和 子序列。
  • 使用变量i[0, N-1]范围内迭代并执行以下步骤:
    • 如果arr[i] > K ,继续遍历数组的元素。
    • 如果arr[i][(K+1)/2, K]范围内,则返回当前元素的索引作为答案并终止循环。
    • 如果arr[i] +totalSum小于K,则将当前元素添加到totalSum并在向量ans中添加索引i
  • 如果totalSum不在给定范围内,则打印-1,否则打印 矢量答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find a subsequence of the
// given array whose sum of the elements
// is in range [K+1/2, K]
void isSumOfSubSeqInRange(int arr[], int n, int k)
{
 
    // Vector to store the subsequence indices
    vector ans;
 
    // Variable to store the sum of subsequence
    int totalSum = 0;
 
    for (int i = 0; i < n; i++) {
 
        // If the current element is
        // greater than K then move
        // forward
        if (arr[i] > k) {
            continue;
        }
 
        // If the current element is in
        // the given range
        if (arr[i] >= (k + 1) / 2) {
            ans.clear();
            ans.push_back(i);
            totalSum = arr[i];
            break;
        }
        // If current element and totalSum
        // is less than K
        else if (arr[i] + totalSum <= k) {
 
            totalSum += arr[i];
            ans.push_back(i);
        }
    }
 
    // Checking if the totalSum is not
    // in the given range then print -1
    if (2 * totalSum < k) {
        cout << -1 << endl;
        return;
    }
 
    // Otherwise print the answer
    for (int x : ans) {
        cout << x << " ";
    }
    cout << endl;
}
 
// Driver Code
int main()
{
 
    // Given Input
    int arr[] = { 6, 2, 20, 3, 5, 6 };
    int N = 6;
    int K = 13;
 
    // Function Call
    isSumOfSubSeqInRange(arr, N, K);
    return 0;
}


Java
// Java program for the above approach
import java.util.Vector;
 
public class GFG {
 
    // Function to find a subsequence of the
    // given array whose sum of the elements
    // is in range [K+1/2, K]
    static void isSumOfSubSeqInRange(int arr[], int n,
                                     int k)
    {
 
        // Vector to store the subsequence indices
        Vector ans = new Vector<>();
 
        // Variable to store the sum of subsequence
        int totalSum = 0;
 
        for (int i = 0; i < n; i++) {
 
            // If the current element is
            // greater than K then move
            // forward
            if (arr[i] > k) {
                continue;
            }
 
            // If the current element is in
            // the given range
            if (arr[i] >= (k + 1) / 2) {
                ans.clear();
                ans.add(i);
                totalSum = arr[i];
                break;
            }
            // If current element and totalSum
            // is less than K
            else if (arr[i] + totalSum <= k) {
 
                totalSum += arr[i];
                ans.add(i);
            }
        }
 
        // Checking if the totalSum is not
        // in the given range then print -1
        if (2 * totalSum < k) {
            System.out.println(-1);
            return;
        }
 
        // Otherwise print the answer
        for (int x : ans) {
            System.out.print(x + " ");
        }
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Given Input
        int arr[] = { 6, 2, 20, 3, 5, 6 };
        int N = 6;
        int K = 13;
 
        // Function Call
        isSumOfSubSeqInRange(arr, N, K);
    }
}
// This code is contributed by abhinavjain194


Python3
# Python3 program for the above approach
 
# Function to find a subsequence of the
# given array whose sum of the elements
# is in range [K+1/2, K]
def isSumOfSubSeqInRange(arr, n, k):
     
    # Vector to store the subsequence indices
    ans = []
 
    # Variable to store the sum of subsequence
    totalSum = 0
 
    for i in range(n):
         
        # If the current element is
        # greater than K then move
        # forward
        if (arr[i] > k):
            continue
 
        # If the current element is in
        # the given range
        if (arr[i] >= (k + 1) / 2):
            ans.clear()
            ans.append(i)
            totalSum = arr[i]
            break
 
        # If current element and totalSum
        # is less than K
        elif (arr[i] + totalSum <= k):
            totalSum += arr[i]
            ans.append(i)
 
    # Checking if the totalSum is not
    # in the given range then print -1
    if (2 * totalSum < k):
        print(-1)
        return
 
    # Otherwise print the answer
    for x in ans:
        print(x, end = " ")
     
# Driver Code
if __name__ == '__main__':
     
    # Given Input
    arr = [ 6, 2, 20, 3, 5, 6 ]
    N = 6
    K = 13
 
    # Function Call
    isSumOfSubSeqInRange(arr, N, K)
 
# This code is contributed by bgangwar59


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to find a subsequence of the
    // given array whose sum of the elements
    // is in range [K+1/2, K]
    static void isSumOfSubSeqInRange(int[] arr, int n,
                                     int k)
    {
 
        // Vector to store the subsequence indices
        List ans = new List();
 
        // Variable to store the sum of subsequence
        int totalSum = 0;
 
        for (int i = 0; i < n; i++) {
 
            // If the current element is
            // greater than K then move
            // forward
            if (arr[i] > k) {
                continue;
            }
 
            // If the current element is in
            // the given range
            if (arr[i] >= (k + 1) / 2) {
                ans.Clear();
                ans.Add(i);
                totalSum = arr[i];
                break;
            }
           
            // If current element and totalSum
            // is less than K
            else if (arr[i] + totalSum <= k) {
 
                totalSum += arr[i];
                ans.Add(i);
            }
        }
 
        // Checking if the totalSum is not
        // in the given range then print -1
        if (2 * totalSum < k) {
            Console.WriteLine(-1);
            return;
        }
 
        // Otherwise print the answer
        foreach(int x in ans)
        {
            Console.Write(x + " ");
        }
        Console.WriteLine();
    }
 
    // Driver code
    static public void Main ()
    {
       
        // Given Input
        int[] arr = { 6, 2, 20, 3, 5, 6 };
        int N = 6;
        int K = 13;
 
        // Function Call
        isSumOfSubSeqInRange(arr, N, K);
    }
}
 
// This Code is contributed by ShubhamSingh10


Javascript


输出
0 1 3 

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