Wednesday, December 6, 2023

Largest Number At Least Twice of Others

 


There is an integer array nums where the largest integer is unique.

The task is to determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.

 

Example 1:

Input: nums = [3,6,1,0]

Output: 1

Explanation: 6 is the largest integer.

For every other number in the array x, 6 is at least twice as big as x.

The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1,2,3,4]

Output: -1

Explanation: 4 is less than twice the value of 3, so we return -1.

 

Constraints:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • The largest element in nums is unique.

 

class Solution {

    public int dominantIndex(int[] nums) {

        if (nums == null || nums.length == 0) return -1;

        Arrays.sort(nums);

        int max = nums[nums.length-1];

        for (int i = 0; i < nums.length-1; i++) {

            if ( 2 * nums[i] > max) {

                return -1;

            }

        }

        return 1;

    }

}

Test cases: [0]=>1, [0,1,2] => 1, [0,1,0] => 1, [-1,0,1] => 1, [0,0] =>-1, [-4,-3,-2,-1] => 1

https://1drv.ms/w/s!Ashlm-Nw-wnWhNNPo73BVh-_5icutw?e=lPqYlv

Monday, December 4, 2023

 

The following is a case study for an automation involving a web request.

A PowerShell script written to invoke a remote method by sending a web request works find when executed locally on a PowerShell Terminal but fails to run the command when the script is part of an automation workflow aka runbook. The error encountered is “Name or service not known.” even though the remote method is hosted in an app service. If the app service were denying the request, a 403 statuscode might have appeared in the error but this is not the case. The request does not reach the target. The following article explains how to diagnose this situation.

Before we begin diagnosing the specific cmdlet, it is important to check that the associated module is imported. This can be done with `ipmo Microsoft.PowerShell.Utility` directive. It is also necessary to ensure that the execution policy of the script permits the call. This can be relaxed with `Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force -Scope Process` command. Also, the logged in user or identity making the call must have the necessary permissions to do so or assign the web app contributor role to the principal.

First, the automation, by its nature, cannot be interactive, so the parameters must be checked to include an option to progress without involvement. For example, the $progressPreference = “silentlyContinue” may help here.

Second, the parameter to debug the call might yield more information than regular invocation. The ‘-Debug’ parameter, for example, may indicate that the TLS handshake failed which resulted in the call not going through. It could also indicate a timeout in getting a response when the request was valid indicating other reasons why the call could not go through.

When the TLS handshake fails, it might most likely arise from the certificate validation. A caller making a web request can choose to skip the validation when the method is to a target that falls under the control of the owner owning the automation as well as the app service.  A PowerShell method to trust all certificates might be something as simple as:

add-type @"

    using System.Net;

    using System.Security.Cryptography.X509Certificates;

    public class TrustAllCertsPolicy : ICertificatePolicy {

        public bool CheckValidationResult(

            ServicePoint srv, X509Certificate certi,

            WebRequest req, int certificateIssue) {

            return true;

        }

    }

"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

 

A try-catch handler around the request can also indicate not only the exception but also other modules that might be involved in the request from the associated stacktrace. For example,

try {

    Invoke-RestMethod -Method Get -Uri APISERVER/api/v1/namespaces/default/pods/ -Headers $headers

}

catch {

    $_.Exception | Format-List -Force

}

may indicate the error when it would otherwise be omitted from the logs.

It is also possible that the target might not be reachable over the network and this can be diagnosed with:

$DnsCheck = Resolve-DnsName $uri -ErrorAction SilentlyContinue

Similarly, other parameters to the web-request can also help here such as –UseBasicParsing to indicate that this is not a web request from a browser, -Proxy ‘http://w.x.y.z:80’ -ProxyCredential $creds where the credentials are obtained from $creds = New-AzADSpCredential -ServicePrincipalName <ServicePrincipalName> and specifying the method such as with -Method GET.

These are some of the ways in which the web request can be made to succeed.

Sunday, December 3, 2023

 

Maximum Sum With Exactly K Elements

0-indexed integer array nums and an integer k are given. The task is to perform the following operation exactly k times in order to maximize your score:

  1. Select an element m from nums.
  2. Remove the selected element m from the array.
  3. Add a new element with a value of m + 1 to the array.
  4. Increase your score by m.

The maximum score that can be achieved after performing the operation exactly k times must be returned.

 

Example 1:

Input: nums = [1,2,3,4,5], k = 3

Output: 18

Explanation: We need to choose exactly 3 elements from nums to maximize the sum.

For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6]

For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7]

For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8]

So, we will return 18.

It can be proven, that 18 is the maximum answer that we can achieve.

Example 2:

Input: nums = [5,5,5], k = 2

Output: 11

Explanation: We need to choose exactly 2 elements from nums to maximize the sum.

For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6]

For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7]

So, we will return 11.

It can be proven, that 11 is the maximum answer that we can achieve.

 

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • 1 <= k <= 100

 

class Solution {

    public int maximizeSum(int[] nums, int k) {

        if (nums == null || nums.length == 0 || k <= 0) return 0;

        Arrays.sort(nums);

        int sum = 0;

        int val = nums[nums.length-1];

        for (int i = 0; i < k; i++){

            sum += val;

            val += 1;

        }

        return sum;

    }

}

 

Nums = [3], k = 3 => sum = 12

Nums = [1,2,3], k = 3 => sum = 12

Nums = [-1,-1,-1], k = 3 => sum = 0

Nums = [-1,0,1], k = 1 => sum = 1 

 

Saturday, December 2, 2023

 This is a continuation of previous articles on IaC shortcomings and resolutions. The networking resources for private plane connectivity are ubiquitous and several within any deployment. As the deployment grows with age, the versions of the toolset and definitions also change. New properties are added while the old ones are deprecated. Subnets, for instance, can be created with different definitions and property values but with the same module. By nature of subnets delegated to a resource type, there will be several within a virtual network used with a deployment. When the new properties are added to the definition, many of the existing properties might require an opposite value with these new properties while the others might work with the default value. The same goes for different environments where the module is applied. Changing the definitions might pose a risk across many resources that are hosted on the subnets. If there are disruptions, they could manifest in different scenarios,

This could be overcome by staging the changes progressively and in an incremental manner such that the round of tests is minimized and only applies to the changes made. The first step should be to update the toolset before any changes are made  Many of the existing resource types might need adjustments with new toolsets although backward compatibility if a standard feature as toolset versions is incremented. Once this is done, the existing definitions must be assigned to a reference for their source before a new definition is used. If they do not have a reference, they will likely point to the latest and updating the source to a new definition will affect more resources than intended. Next, the common definition must be updated, and a new tag must be generated so that it can be referenced only from those callers that require the new definition. One the reference is available, all the resources in the deployment that require the new definition must point to the new reference. Then their properties must be replaced with new properties in such a way that there is no change to the current infrastructure. Some of this might be counterintuitive in terms of say Boolean values assigned to certain properties but the goal must be to have no changes to the infrastructure after complying with the new syntax. This way there will not be a need to test all the resources attached to the subnets, which is quite a daunting task. Finally, changes must be made on a case-by-case basis so that those cases can be tested independent of the overall infrastructure. When all the changes have been made to revise the infrastructure, the definitions, the resource properties, and the fine tunings to individual resources, then a closure can be applied by setting up alerts and notifications as the resource-types demand. 

One of the advantages of making selective changes is that the business can weigh in on their priorities and release dates. It does not need to be done all at once and it might even be beneficial to get their acceptance after each change. The requirements from the business usually affect one or more environments, so prioritizing by environment is a natural order. It is also possible to include the changes compare resources from different scenarios which will inevitably help with troubleshooting unexpected behaviors from deployed resources. Together with the scenarios and infrastructure, it would be easier to narrow down the potential issues and determine the course of action for their resolutions. Similarly, we can leverage the compiler planning and execution stages to spot errors before they are caught by actual testing. 

In this way, changes affect several dozens of resources can be made in a safe and efficient manner.


Friday, December 1, 2023

 

This is a summary of a book titled “The Leader’s checklist – 16 mission critical principles” written by Michael Useem and published by the Wharton School Press 2021. He is a is a professor of management and the faculty director of the Center for Leadership and Change Management and the McNulty Leadership Program at the Wharton School of the University of Pennsylvania. Everybody draws up a list of tasks they need to get to. Leadership is also best served by a checklist only that it varies for the level of leadership.

A team leader’s checklist might include these items:

Educate – Build your team members’ knowledge and cognitive skills.

Plan – Establish specific goals and defined, varied tasks for your team members.

Energize – Encourage team members to be flexible and evolve as demands change.

Foster diversity and be inclusive – Seed your teams with people from a variety of backgrounds.

A board member’s leadership checklist could include:

Strategize – Board members must make sure their company’s executives generate well-developed strategic plans to create organizational value and increase competitive advantage.

Set a tone – To collaborate effectively, board members must show restraint and be diplomatic.

Mentor others – Board members must teach future leaders.

Advise – Board members serve in partnership with their company’s CEO who should be able to trust them to provide their best counsel.

The team of teams’ leader needs a checklist that includes these priorities: 

Unify – Champion a “common mind-set” and collaborative culture. 

Structure – Team-of-teams leaders organize around a “cohesive inner circle.” Each member shares a particular vision and offers the group relevant expertise.

Bonding – Team-of-teams leaders foster “strong lateral” bonds across divisional boundaries to develop a unified perspective among their team members.

Collaborate – In the team-of-teams framework, leaders of individual groups work toward their goals in collaboration with other teams.

Along with a wealth of stories, anecdotes and  research findings, this book provides preparation for the future while staying focused and organized.`

The guiding principles for the checklists both published and customized are mentioned by these sixteen principles: articulate a vision, think and act strategically, honor the room, take charge and lead change, act decisively, communicate persuasively, motivate the workforce, embrace the front lines, build leadership in others, manage relations, identify personal implications, convey your character, dampen over-optimism and excessive pessimism, build a diverse top team, place common interest first, and think like a CEO.