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;
        }
    }
    

      

  • 相关阅读:
    PAT 1025. 反转链表 (25)
    PAT 1024. 科学计数法 (20)
    PAT 1076. Forwards on Weibo (30)
    C++——cout输出小数点后指定位数
    PTA 06-图3 六度空间 (30分)
    PTA 06-图2 Saving James Bond
    PTA
    浙大PTA
    浙大PTA
    随机密码生成
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11236536.html
Copyright © 2011-2022 走看看