zoukankan      html  css  js  c++  java
  • best-time-to-buy-and-sell-stock-ii

    /**
    * @author gentleKay
    * Say you have an array for which the i th 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).
    *
    * 假设您有一个数组,其中第i个元素是第一天给定股票的价格。
    * 设计了一种求最大利润的算法。您可以完成任意多的交易
    * (即,购买一份股票并多次出售一份股票)。
    * 但是,您不能同时进行多个交易
    * (即,您必须在再次购买之前出售股票)。
    */

    /**
     * 
     * @author gentleKay
     * Say you have an array for which the i th 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).
     * 
     * 假设您有一个数组,其中第i个元素是第一天给定股票的价格。
     * 设计了一种求最大利润的算法。您可以完成任意多的交易
     * (即,购买一份股票并多次出售一份股票)。
     * 但是,您不能同时进行多个交易
     * (即,您必须在再次购买之前出售股票)。
     */
    
    public class Main06 {
    
    	public static void main(String[] args) {
    		int[] prices = {1,4,2};
    		System.out.println(Main06.maxProfit(prices));
    	}
    	
    	public static int maxProfit(int[] prices) {
    		if (prices == null || prices.length < 2) {
    			return 0;
    		}
    		
    		int num = 0;
    		for (int i=1;i<prices.length;i++) {
    			if (prices[i] > prices[i-1]) {
    				num = num + prices[i] - prices[i-1];
    			}
    		}
            return num;
        }
    }
    

      

  • 相关阅读:
    高等数学(6) 无穷小和无穷大
    高等数学(5) 函数的极限
    高等数学(4) 数列与数列极限
    实时音视频互动系列(下):基于 WebRTC 技术的实战解析
    实时音视频互动系列(上):又拍云UTUN网络详解
    免费SSL&付费SSL证书,该如何选择?
    直播卡顿原因详解及优化
    实战解析 | 同步音视频解决方案
    从Html5直播到互动直播,看直播协议的选择
    如何将HLS延时缩短至4秒,HLS+技术详解
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11236536.html
Copyright © 2011-2022 走看看