Php-interview questions: use the least iteration to convert all elements of the array to the average value (balance)

Source: Internet
Author: User
Input: Array. all values are non-negative integers. target: convert each value of the array to the average value of all values, and use the least number of iterations transformation method: subtract one from each value, add one to the value next to the left or right. The first value of the array can only be 1 to the right, and the last value can be 1 to the left. during the transformation, all values in the number Group cannot be negative. Example 1: Input: [, 3] first: [, 3] [, 2] second: [, 2] Example 2, 1] [, 2] [, 3] [,] Example 3... php interview question algorithm array

Input: Array. all values are non-negative integers.
Objective: to convert each value of an array to the average value of all values, with the minimum number of iterations
Conversion Method: subtract one from a value to add one next to the value on the left or right. The first value of the array can only be 1 to the right, and the last value can be 1 to the left. during the transformation, all values in the number Group cannot be negative.
Example 1:
Input: [0, 3, 3]
First time: [1, 2, 3] [1, 3, 2]
Second: [2, 2, 2]
Example 2
[2, 4, 6, 2, 1]
[3, 3, 5, 2, 2]
[3, 3, 4, 2, 3]
[3, 3, 3, 3, 3]
Example 3
[1, 0, 7, 0]
[1, 1, 6, 0]
[2, 1, 5, 0]
[2, 2, 4, 0]
[2, 2, 3, 1]
[2, 2, 2, 2]
Is there any good algorithm to solve this problem? the example is not the only solution. The solution is implemented in php.

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.