From f93c730138162abeccf02ae1e7c47cb6d2e78f75 Mon Sep 17 00:00:00 2001 From: Disha Thakurata <146114938+dishathakurata@users.noreply.github.com> Date: Wed, 11 Dec 2024 22:24:11 +0530 Subject: [PATCH] Create Minimum sum --- Minimum sum | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Minimum sum diff --git a/Minimum sum b/Minimum sum new file mode 100644 index 0000000..e3b1611 --- /dev/null +++ b/Minimum sum @@ -0,0 +1,77 @@ +//Minimum sum + +import java.io.*; +import java.lang.*; +import java.util.*; + +class GFG { + public static void main(String args[]) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int t = Integer.parseInt(br.readLine()); + + while (t-- > 0) { + String arr[] = br.readLine().split(" "); + int a[] = new int[arr.length]; + + for(int i = 0; i < arr.length; i++) { + a[i] = Integer.parseInt(arr[i]); + } + + Solution obj = new Solution(); + int f = 0; + String A = obj.minSum(a); + System.out.println(A); + System.out.println("~"); + } + } +} + +class Solution { + String minSum(int[] arr) { + Arrays.sort(arr); + StringBuilder s1 = new StringBuilder(); + StringBuilder s2 = new StringBuilder(); + + for(int i = 0; i < arr.length; i++) { + if(i % 2 == 0) { + s1.append(arr[i]); + } + else { + s2.append(arr[i]); + } + } + + return addString(s1, s2); + } + + static String addString(StringBuilder s1, StringBuilder s2) { + int i = s1.length() - 1; + int j = s2.length() - 1; + int carry = 0; + StringBuilder res = new StringBuilder(); + + while(i >= 0 || j >= 0 || carry > 0) { + int sum = carry; + + if(i >= 0) { + sum += (s1.charAt(i) - '0'); + } + if(j >= 0) { + sum += (s2.charAt(j) - '0'); + } + + res.append(sum % 10); + carry = sum / 10; + i--; + j--; + } + + while(res.length() > 0 && res.charAt(res.length() - 1) == '0') { + res.deleteCharAt(res.length() - 1); + } + + res.reverse(); + + return res.toString(); + } +}