A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.)

We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'.

Return the minimum number of flips to make S monotone increasing.

Example 1:

Input: "00110"
Output: 1
Explanation: We flip the last digit to get 00111.

Example 2:

Input: "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.

Example 3:

Input: "00011000"
Output: 2
Explanation: We flip to get 00000000.

Note:

  1. 1 <= S.length <= 20000
  2. S only consists of '0' and '1' characters.

Idea 1. 由结果推算,if monotonic increasing string is composed of x zeros and (n-x) ones, based on the number of ones on the left and right side of str[x], the number of flips can be calculated as ones[x] + (n-x - (ones[n] - ones[x])), another example to use prefix sum to caculate ones.

flip from '1' -> '0' on the left: ones[x]

flip from '0' -> '1' on the right: n - x - (ones[n] - ones[x]) or scan the array from right to left

仔细corner case, 全部都是'0' or '1' monotonic increasing string.

Time complexity: O(n)

Space complexity: O(n)

 class Solution {
public int minFlipsMonoIncr(String S) {
int n = S.length();
int[] ones = new int[n+1];
for(int i = 1; i <=n; ++i) {
ones[i] = ones[i-1] + S.charAt(i-1) - '0';
} int result = Integer.MAX_VALUE;
for(int i = 0; i <= n; ++i) {
result = Math.min(result, ones[i] + (n - i) - (ones[n] - ones[i]));
} return result;
}
}

Idea 1.b No need to build ones array, the number of ones can be computed while looping the array, just need the total number of ones in advance

Time complexity: O(n)

Space complexity: O(1)

 class Solution {
public int minFlipsMonoIncr(String S) {
int n = S.length();
int totalOnes = 0;
for(int i = 0; i < S.length(); ++i) {
totalOnes += S.charAt(i) - '0';
}
int ones = 0; int result = Integer.MAX_VALUE;
for(int i = 0; i <= n; ++i) {
if(i >= 1) {
ones += S.charAt(i-1) - '0';
}
result = Math.min(result, ones + (n - i) - (totalOnes - ones));
} return result;
}
}

稍微简洁一点,把全身1的情况做初始值

 class Solution {
public int minFlipsMonoIncr(String S) {
int n = S.length();
int totalOnes = 0;
for(int i = 0; i < S.length(); ++i) {
totalOnes += S.charAt(i) - '0';
}
int ones = 0; int result = n - totalOnes;
for(int i = 1; i <= n; ++i) {
ones += S.charAt(i-1) - '0';
result = Math.min(result, ones + (n - i) - (totalOnes - ones));
} return result;
}
}

Idea 2. Dynamic programming, 网上看到的更赞的方法, let dp[i-1] be the minimum number of flips to make S.substring(0, i) is monotonic increasing, how to extend the solution for S.charAt(i)?

dp[i] = dp[i-1] if S.charAt(i) == '1', nothing needed, as it still satisfy monotonic increasing string.

dp[i] = Math.min(ones[i-1], dp[i-1] + 1), if S.chart(i) == '0' either flip all the previous ones to 0; or flip the current '0' to '1' since S.substring(0, i) is monotonice, add '1' still satisfies the conidtion.

Time complexity: O(n)

Space complexity: O(n)

 class Solution {
public int minFlipsMonoIncr(String S) {
int n = S.length();
int[] dp = new int[n+1];
int ones = 0;
for(int i = 1; i <= n; ++i) {
if(S.charAt(i-1) == '1') {
dp[i] = dp[i-1];
++ones;
}
else {
dp[i] = Math.min(dp[i-1] + 1, ones);
}
} return dp[n];
}
}

Idea 2.b the above formula shows the current dp depends only on the previous number, the array dp[] is not needed

Time complexity: O(n)

Space complexity: O(1)

 class Solution {
public int minFlipsMonoIncr(String S) {
int n = S.length();
int dp = 0;
int ones = 0;
for(int i = 1; i <= n; ++i) {
if(S.charAt(i-1) == '1') {
++ones;
}
else {
dp = Math.min(dp + 1, ones);
}
} return dp;
}
}

Flip String to Monotone Increasing LT926的更多相关文章

  1. LC 926. Flip String to Monotone Increasing

    A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), ...

  2. [Swift]LeetCode926. 将字符串翻转到单调递增 | Flip String to Monotone Increasing

    A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), ...

  3. 926. Flip String to Monotone Increasing

    A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), ...

  4. [LeetCode] 926. Flip String to Monotone Increasing 翻转字符串到单调递增

    A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), ...

  5. 【leetcode】926.Flip String to Monotone Increasing

    题目如下: A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possib ...

  6. 【LeetCode】926. Flip String to Monotone Increasing 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Prefix计算 动态规划 参考资料 日期 题目地址 ...

  7. [LeetCode] Monotone Increasing Digits 单调递增数字

    Given a non-negative integer N, find the largest number that is less than or equal to N with monoton ...

  8. [Swift]LeetCode738. 单调递增的数字 | Monotone Increasing Digits

    Given a non-negative integer N, find the largest number that is less than or equal to Nwith monotone ...

  9. 738. Monotone Increasing Digits 单调递增的最接近数字

    [抄题]: Given a non-negative integer N, find the largest number that is less than or equal to N with m ...

随机推荐

  1. 服务器上运行程序Out of memory 解决办法

    ****** 服务器上跑过程序经常能遇到out of memory 这个问题,下面是我经常在实验室碰到的解决方法. 1.使用命令nvidia-smi,看到GPU显存被占满: 2.尝试使用 ps aux ...

  2. Python爬虫与数据分析之爬虫技能:urlib库、xpath选择器、正则表达式

    专栏目录: Python爬虫与数据分析之python教学视频.python源码分享,python Python爬虫与数据分析之基础教程:Python的语法.字典.元组.列表 Python爬虫与数据分析 ...

  3. 对抗生成网络-图像卷积-mnist数据生成(代码) 1.tf.layers.conv2d(卷积操作) 2.tf.layers.conv2d_transpose(反卷积操作) 3.tf.layers.batch_normalize(归一化操作) 4.tf.maximum(用于lrelu) 5.tf.train_variable(训练中所有参数) 6.np.random.uniform(生成正态数据

    1. tf.layers.conv2d(input, filter, kernel_size, stride, padding) # 进行卷积操作 参数说明:input输入数据, filter特征图的 ...

  4. 开源小程序CMS网站, JeeWx-App-CMS 1.1 版本升级发布,持续更新!

    JeeWx-App-CMS开源小程序CMS网站,持续更新ing~ JeeWx-App-CMS 是jeewx开发的小程序网站开源项目,基于小程序wepy语言,具备cms网站的基本功能,能够打造简单易用的 ...

  5. ISO 2501 quality model division 学习笔记

    作为一个测试,学习质量模型,能够帮你 在测试设计的时候,从多个角度来思考测试用例的设计.而不仅仅是从 功能上, 同时 需要结合自己的产品,选择自己的侧重点,譬如我们公司的产品,安全性这一块 就比较小, ...

  6. 源码解析之ConcurrentHashmap

    ConcurrentHashmap算是我看的集合源码里最难理解的了(当然ConcurrentLinkedList虽然代码少但理解起来也累),在Java1.8版本中DougLea大师巧通过妙地代码把锁粒 ...

  7. Python数据分析学习(二):Numpy数组对象基础

    1.1数组对象基础 .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { bord ...

  8. PhoenixFD插件流体模拟——UI布局【Input】详解

    Liquid Input 流体输入 本文主要讲解Input折叠栏中的内容.原文地址:https://docs.chaosgroup.com/display/PHX3MAX/Liquid+Input 主 ...

  9. Python下划线简介

    Python中下划线的5种含义 分享一篇文章:The Meaning of Underscores in Python. 本文介绍了Python中单下划线和双下划线("dunder" ...

  10. linux搭建zabbix server

    一.linux配置jdk 1.安装rpm包,安装完成位置:/usr/java/jdk1.8.0_152 2.配置环境变量/etc/profile: JAVA_HOME=/usr/java/jdk1.. ...