pseudocode - Finding smallest value in array and storing in subarray most efficently -


given array a, calculate new array b of size n, such b[i] = min (0 ≤ j ≤i) a[j]. in other words, b[i] should store minimum element in subarray of indices 0 i, inclusive.

input: a[7, 3, 4, 2, 15, 11, 16, 7, 18, 9, 11, 10]
output: b[7, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2]

i'm trying create efficient algorithm solving problem. attempt @ psuedocode.

minelement(a):  b[n]; //empty array   for(i = 0; < a.length()-1; i++)    if(a[i] < in b[])     b[i] = a[i] 

i'm having hard time trying implement logic.

you need variable currentmin keep track of minimum value in portion of input array processed.

func calculate(nums:[int]) -> [int] {     guard !nums.isempty else { return [] }     var currentmin = nums[0]      var output: [int] = []     num in nums {         currentmin = min(currentmin, num)         output.append(currentmin)     }      return output } 

so inside loop can update currentmin variable , append value output.

the provided implementation in swift.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -