Manasa is out on a hike with friends. She finds a trail of stones with numbers on them. She starts following the trail and notices that any two consecutive stones' numbers differ by one of two values. Legend has it that there is a treasure trove at the end of the trail. If Manasa can guess the value of the last stone, the treasure will be hers.
Example 1:
Input:2 3 1 2 4 10 100
Output: 2 3 4 30 120 210 300
Approach
Java
import java.util.Arrays;import java.util.Set;import java.util.TreeSet;public class ManasaandStones {public static void main(String[] args) {int n = 4;int a = 10;int b = 100;int res[] = stones(n, a, b);System.out.println(Arrays.toString(res));}public static int[] stones(int n, int a, int b) {int arr[] = new int[n + 1];int brr[] = new int[n + 1];arr[0] = 0;brr[0] = 0;for (int i = 1; i <= n; i++) {arr[i] = a * i;}for (int i = 1; i <= n; i++) {brr[i] = b * i;}Set<Integer> st = new TreeSet<>();for (int i = 0; i < n; i++) {st.add(arr[i] + brr[n - i - 1]);}int aa[] = st.stream().mapToInt(Integer::intValue).toArray();return aa;}}
C++
#include <bits/stdc++.h>using namespace std;int main(){long long int t;cin>>t;while(t--){long long int n,a,b;cin>>n>>a>>b;long long int arr[n+1],brr[n+1];arr[0]=0;brr[0]=0;for(long long int i=1;i<=n;i++){arr[i]=a*i;}for(long long int i=1;i<=n;i++){brr[i]=b*i;}set<long long int > st;for(long long int i=0;i<n;i++){st.insert(arr[i]+brr[n-i-1]);}for(auto it=st.begin();it!=st.end();it++)cout<<*it<<" ";cout<<"\n";}return 0;}//Time Complexity:O(n)
No comments:
Post a Comment