zoukankan      html  css  js  c++  java
  • [leetcode]Best Time to Buy and Sell Stock II

    Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). 

    算法思路:

    计算出每个增区间的差值。求总和。

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if(prices == null || prices.length < 2) return 0;
     4         int pre = 0,  post = 1,length = prices.length;
     5         int buy = 0,profit = 0;
     6         for(int i = 0; i < prices.length; i++,pre = i - 1, post = i + 1){
     7             if(post < length && prices[pre] >= prices[i] && prices[post] > prices[i]){
     8                 buy = prices[i];
     9             }
    10             if( prices[i] > prices[pre] && (post != length ? prices[i] >= prices[post] : true) ){
    11                 profit += prices[i] - buy;
    12             }
    13         }
    14         return profit;
    15     }
    16 }

    第二遍优化:

    上文代码是确定增区间的起始点,事实上不必确定起始点,只要关心相邻两点是否增长即可。

    即:prices = {1,2,3,4,2,1}

    前文做法是确定了增区间为1 ~ 4,因此受益为 4 - 1 = 3

    本文做法是只与前一天作比较,如果有收益,则做交易,例如该例:

    从第二个下标开始遍历,发现2 > 1,则做一次交易,收益为 2 - 1 = 1

    往后遍历发现3 > 2 ,再做一次交易,3 - 2 = 1

    如此往复

    总收益为:(2 - 1) + (3 - 2) + (4 - 3) = 3

    代码相对而言就简单多了

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if(prices == null || prices.length < 2) return 0;
     4         int length = prices.length;
     5         int max = 0;
     6         for(int i = 1; i < length; i++){
     7             if(prices[i] > prices[i - 1]){
     8                 max += prices[i] - prices[i - 1];
     9             }
    10         }
    11         return max;
    12     }
    13 }
  • 相关阅读:
    JVM调优方法笔记
    JVM调优方法笔记
    JavaScript实现选择排序
    自动安装带nginx_upstream_check_module模块的Nginx脚本
    自动安装带nginx_upstream_check_module模块的Nginx脚本
    自动安装带nginx_upstream_check_module模块的Nginx脚本
    简单的文件上传html+ashx
    【转】建构修正版 Casper 协议
    【转】为什么去中心化兑换协议很重要
    【转】当我们说“区块链是无需信任的”,我们的意思是
  • 原文地址:https://www.cnblogs.com/huntfor/p/3895969.html
Copyright © 2011-2022 走看看