Square Transaction

Square Inc. processes thousands of transactions daily amounting to millions of dollars. They also have a daily target that they must achieve. Given a list of transactions done by Square Inc. and a daily target your task is to determine at which transaction does Square achieves the same.

Example 1:

Input : t=5
1 2 1 3 4
3
4
2
10
Output:
3
2
5

Approach:

Java

import java.util.Scanner;

public class SquareTransaction {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        in.nextLine();
        long[] arr = new long[N];
        long[] runninSum = new long[N];
        for (int i = 0; i < N; i++) {
            arr[i] = in.nextLong();
            if (i == 0)
                runninSum[i] = arr[i];
            else
                runninSum[i] = runninSum[i - 1] + arr[i];
        }
        in.nextLine();
        long test = in.nextLong();
        for (long i = 0; i < test; i++) {
            long sum = in.nextLong();
            long index = squareTransaction(runninSum, sum);
            System.out.println(index);
//          in.nextLine();
        }
        in.close();
    }

    // linear search for get index
    private static long squareTransaction(long[] runninSumlong sum) {
        int index = 0;
        for (long i : runninSum) {
            index++;
            if (i >= sum)
                return index;

        }
        return -1;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;
int main()
{
   //fast input output
   ios_base::sync_with_stdio(false);
   cin.tie(NULL);
   long long n;
   cin>>n;
   long long a[n];
   for(long long i=0;i<n;i++)
     cin>>a[i];
   long long q;
   cin>>q;
   long long sum[n];
   sum[0]=a[0];
   for(long long i=1;i<n;i++)
      sum[i]=sum[i-1]+a[i];
   while(q--)
     {
        long long x;
        cin>>x;
          long long ans=-1;
        for(long long i=0;i<n;i++)
           {
             if(sum[i]>=x)
              {
                 ans=i+1;
                 break;
              }
          }
         if(x>sum[n-1])
            cout<<-1<<"\n";
         else if(ans==-1)
            cout<<n<<"\n";
         else
           cout<<ans<<"\n";
     }
}



No comments:

Post a Comment