博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 1130. Minimum Cost Tree From Leaf Values
阅读量:4621 次
发布时间:2019-06-09

本文共 2223 字,大约阅读时间需要 7 分钟。

原题链接在这里:

题目:

Given an array arr of positive integers, consider all binary trees such that:

  • Each node has either 0 or 2 children;
  • The values of arr correspond to the values of each leaf in an in-order traversal of the tree.  (Recall that a node is a leaf if and only if it has 0 children.)
  • The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.

Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node.  It is guaranteed this sum fits into a 32-bit integer.

Example 1:

Input: arr = [6,2,4]Output: 32Explanation:There are two possible trees.  The first has non-leaf node sum 36, and the second has non-leaf node sum 32.    24            24   /  \          /  \  12   4        6    8 /  \               / \6    2             2   4

Constraints:

  • 2 <= arr.length <= 40
  • 1 <= arr[i] <= 15
  • It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than 2^31).

题解:

From the example, see that it is better to remove smaller element first.

Remove small element i and the cost is arr[i] * Math.min(arr[i-1], arr[i+1]). minimum cost happens between smaller values of i-1 and i+1.

Remove until there is only one element and sum of cost is the answer.

Use stack to maintain decreasing order, when there is bigger value num, then pop small value arr[i] and acculate the cost arr[i] * Math.min(num, stk.peek()).

Time Complexity: O(n). n = arr.length.

Space: O(n).

AC Java:

1 class Solution { 2     public int mctFromLeafValues(int[] arr) { 3         if(arr == null || arr.length < 2){ 4             return 0; 5         } 6          7         int res = 0; 8         Stack
stk = new Stack<>(); 9 stk.push(Integer.MAX_VALUE);10 for(int num : arr){11 while(stk.peek() <= num){12 int mid = stk.pop();13 res += mid*Math.min(stk.peek(), num);14 }15 16 stk.push(num);17 }18 19 while(stk.size() > 2){20 res += stk.pop()*stk.peek();21 }22 23 return res;24 }25 }

跟上.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11457644.html

你可能感兴趣的文章
一文搞懂Java环境,轻松实现Hello World!
查看>>
hash实现锚点平滑滚动定位
查看>>
也谈智能手机游戏开发中的分辨率自适应问题
查看>>
关于 IOS 发布的点点滴滴记录(一)
查看>>
《EMCAScript6入门》读书笔记——14.Promise对象
查看>>
CSS——水平/垂直居中
查看>>
Eclipse连接mysql数据库jdbc下载(图文)
查看>>
Python中Selenium的使用方法
查看>>
三月23日测试Fiddler
查看>>
20171013_数据库新环境后期操作
查看>>
poj 1654 && poj 1675
查看>>
运维派 企业面试题1 监控MySQL主从同步是否异常
查看>>
Docker 版本
查看>>
poj 1753 Flip Game
查看>>
在深信服实习是怎样的体验(研发测试岗)
查看>>
Linux免密码登陆
查看>>
SpringMVC中文件的上传(上传到服务器)和下载问题(二)--------下载
查看>>
Socket & TCP &HTTP
查看>>
osip及eXosip的编译方法
查看>>
Hibernate composite key
查看>>