Sunny and Johnny like to pool their money and go to the ice cream parlor. Johnny never buys the same flavor that Sunny does. The only other rule they have is that they spend all of their money.
Given a list of prices for the flavors of ice cream, select the two that will cost all of the money they have.
Example:
Input: m=4, n=5, arr[]={1,4,5,3,2}
Output: 1 4
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class IceCreamParlor {public static void main(String[] args) {int m = 4;int[] arr = { 1, 4, 5, 3, 2 };int[] result = icecreamParlor(m, arr);System.out.println(Arrays.toString(result));}private static int[] icecreamParlor(int m, int[] arr) {int n = arr.length;List<Integer> res = new ArrayList<Integer>();int i, j;for (i = 0; i < n - 1; i++)for (j = i + 1; j < n; j++)if (arr[i] + arr[j] == m) {res.add(i + 1);res.add(j + 1);break;}return res.stream().mapToInt(Integer::intValue).toArray();}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> icecreamParlor(int m, vector<int> arr){int n = arr.size();vector<int> res;int i, j;for (i = 0; i < n - 1; i++)for (j = i + 1; j < n; j++)if (arr[i] + arr[j] == m){res.push_back(i + 1);res.push_back(j + 1);break;}return res;}int main(){int m = 4;int n = 5;vector<int> arr = {1, 4, 5, 3, 2};vector<int> result = icecreamParlor(m, arr);for (int i = 0; i < result.size(); i++){cout << result[i];if (i != result.size() - 1){cout << " ";}}cout << "\n";return 0;}
No comments:
Post a Comment