"Leetcode" Array -6 (561)-array Partition I (more abstract topic)

Source: Internet
Author: User

Title Description: Two words are thought-provoking ah ....

Given an array of 2n integers, your task was to group these integers into n pairs of Integer, say (A1, B1), (A2, B2), ..., (an, bn) which makes sum of min (AI, bi) for all I from 1 to n as large as possible.

The general meaning of the feeling topic is to divide the array into a number of two-dollar arrays, summing them in a way that minimizes the value, making and maximizing.

Ideas:

At the beginning of the idea, it is not known right now, is to sort the array, using a pointer to traverse backward , to find the smallest and sum. "Note" The pointer accumulates 2 at a time

"Correct code" once write to ~

1 classSolution {2      Public intArraypairsum (int[] nums) {3         if(nums.length% 2! = 0 | | nums = =NULL) {4             return-1;5         }6 Arrays.sort (nums);7         intMaxsum = 0;8          for(inti = 0; i < nums.length-1;i + = 2) {9Maxsum + = Math.min (Nums[i], nums[i + 1]);Ten         } One         returnmaxsum; A     } -}

Complexity of Time: O (N*LOGN)

Space complexity: O (N*LOGN)

"Leetcode" Array -6 (561)-array Partition I (more abstract topic)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.