zoukankan      html  css  js  c++  java
  • [Array]122. Best Time to Buy and Sell Stock II(obscure)

    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,2,3,4,5,4,2,5],在这个序列中[1,2,3,4,5]和[2,5]为累计和为正数的序列,另外一个知识点就是5-1=(2-1)+(3-2)+(4-3)+(5-4)

    代码:

    int maxProfit(vector<int>& prices) {
            int res = 0;
            for(size_t i = 1; i < prices.size(); i++){
                 res += max(prices[i] - prices[i - 1], 0);
            }
            return res;
        }

      另外一种实现:

    int maxprofit(vector<int>& nums){
    int res = 0;
    size_t n = nums.size();
    for(size_t i = 1; i < n; i++){
    if(nums[i] > nums[i - 1]){
    res += nums[i] - nums[i - 1];
    }
    }
    rerurn res; 
    }
    
    //或者用while
    
    int maxprofit(vector<int>& nums){
    int res = 0;
    size_t n = nums.size();
    while(size_t i < n-1){
    if(nums[i] > nums[i - 1]){
    res += nums[i +1] - nums[i];
    }
    i++;
    }
    rerurn res; 
    }
     
  • 相关阅读:
    hdu 3951(博弈规律)
    hdu 3537(博弈,翻硬币)
    hdu 3032(博弈sg函数)
    hdu 2897(威佐夫博奕变形)
    hdu 1527(威佐夫博奕)
    hdu 2516(斐波拉切博弈)
    FZU 2171(线段树的延迟标记)
    二叉数的遍历
    树和二叉树的互相转换
    树的存储
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7289566.html
Copyright © 2011-2022 走看看